Richard
Richard

Reputation: 4546

twitter regex for displaying text as url but not if it is meant as text

Can someone help me to tweak this regex??

I have this regex for twitter and if I spell a word like this R@chard, it wants to turn it in an URL. On Twitter itself it is displayed correctly.

Erasing the last line is maybe obvious, although I don't know much about forming regex expressions. Maybe there is also a smarter one for use with Twitter?

Also, I have an ajax twitter updater and it displays questionmark placeholders. What are they, and can regex get rid off those?

This is my code

function format_tweet($str) 
    {
$formatted_text = preg_replace('/(\b(www\.|http\:\/\/)\S+\b)/', "<a target='_blank' href='$1'>$1</a>", $str);
$formatted_text = preg_replace('/\#(\w+)/', "<a target='_blank' href='http://search.twitter.com/search?q=$1'>#$1</a>", $formatted_text);
$formatted_text = preg_replace('/\@(\w+)/', "<a target='_blank' href='http://twitter.com/$1'>@$1</a>", $formatted_text);
return $formatted_text;
}

Thanks, Richard

Upvotes: 1

Views: 300

Answers (1)

Alix Axel
Alix Axel

Reputation: 154553

Try:

$formatted_text = preg_replace('/(?:^|\s)[#](\w+)/', "<a target='_blank' href='http://search.twitter.com/search?q=$1'>#$1</a>", $formatted_text);
$formatted_text = preg_replace('/(?:^|\s)[@](\w+)/', "<a target='_blank' href='http://twitter.com/$1'>@$1</a>", $formatted_text);

Regarding the question marks, I've no idea. Maybe I'll be able to help if you post some code.

Upvotes: 1

Related Questions