Search code examples
phpregextwitterhyperlinkpreg-replace

Replace @replies in tweet text with HTML hyperlinks without replacing email addresses


I'm detecting @replies in a Twitter stream with the following PHP code using regexes. In the first pattern, I replace @replies at the beginning of the string; in the second, I replace the @replies which follow a space.

$text = preg_replace('!^@([A-Za-z0-9_]+)!', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
$text = preg_replace('! @([A-Za-z0-9_]+)!', ' <a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);

How can I best combine these two rules without false flagging [email protected] as a reply?


Solution

  • OK, on a second thought, not flagging whatever@email means that the previous element has to be a "non-word" item, because any other element that could be contained in a word could be signaled as an email, so it would lead:

    !(^|\W)@([A-Za-z0-9_]+)!
    

    but then you have to use $2 instead of $1.