Twitter Nicks Format
Here’s a great PHP snippet that scans text and then searches for strings with an “@” symbol attached to it (i.e. Twitter handles like “@name”) and then converts them into linked text format. So basically it’s emulating what Twitter does with “@” symbols and “#” hashtags.
<?php /** parseTwitterNicks * * convert text with format "@foo" to link (mentions) * * @author Jonathan Andres * @param string $str string with twitter nicks * @param mixed string|array $allowed list of nicks allowed * @param string $format template for link * @param bool $toArray return matches as array or string * @return mixed string|array */ function parseTwitterNicks($str, $allowed = 'all', $format = 'default', $toArray = false){ // capture all nicks with format @tweetnick preg_match_all('~@([a-z0-9-_]+)~is', $str, $match); // check template if($format == 'default') $format = 'profile.php?user={nick}'; if(!preg_match('~\{nick\}~', $format)) $format = $format . '{nick}'; // have matches? if(empty($match[1])) return ($toArray ? array() : $str); // save matches $found = array(); // replace matches foreach($match[1] as $nick){ // ignore disallowed nicks if(!empty($allowed) && $allowed != 'all'){ if(is_array($allowed)){ if(!in_array($nick, $allowed)) continue; } } // text to link $url = str_replace('{nick}', $nick, $format); $str = str_replace('@' . $nick, '<a href="' . $url . '" title="' . $nick . '">@' . $nick . '</a>', $str); $found[] = $nick; } return ($toArray ? $found : $str); /* A basic example: ----------------- $string = 'hello friends, I\'m listening @daftPunk and you?'; echo parseTwitterNicks($string, 'all'); return: hello my friends, I'm listening <a href="profile.php?user=daftPunk" title="daftPunk">@daftPunk</a> and you? define template: ----------------- $string = 'hello friends, I\'m listening @daftPunk and you?'; echo parseTwitterNicks($string, 'all', 'http://www.phpsnaps.com/?user={nick}'); return: hello my friends, I'm listening <a href="http://www.phpsnaps.com/?user=daftPunk" title="daftPunk">@daftPunk</a> and you? return array with matches: -------------------------- $string = 'hello my friends, I\'m listening @daftPunk, @dubstep music @skrillex and you?'; $matches = parseTwitterNicks($string, 'all', '', true); print_r($matches); return: Array ( [0] => daftPunk [1] => dubstep [2] => skrillex ) */ } ?>