PHP: trasformare i link testuali in link HTML di uno status di Twitter

Quando dobbiamo effettuare il parsing di un feed (XML o JSON) di Twitter con PHP il problema maggiore che ci si presenta davanti è quello di trasformare gli URL testuali dello status in link HTML. Vediamo come fare.

Possiamo usare la seguente funzione che fa uso delle espressioni regolari:


function linkify_twitter_status($status_text) {

  // URL
  $status_text = preg_replace(
    '/(https?:\/\/\S+)/',
    '<a href="\1">\1</a>',
    $status_text
  );

  // utenti
  $status_text = preg_replace(
    '/(^|\s)@(\w+)/',
    '\1@<a href="http://twitter.com/\2">\2</a>',
    $status_text
  );

  // hash tag
  $status_text = preg_replace(
    '/(^|\s)#(\w+)/',
    '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>',
    $status_text
  );

  return $status_text;
}