I want to find the text property of my twitter status objects and change the @username name to <a href="http:/twitter.com/username">@username</a> . What I have tried so far is as follows:
$pattern = '/([@]{1})([a-zA-Z0-9\_]+)/'; $replace = '<a href="http://twitter.com/\2">\1\2</a>'; $new_string = preg_replace($pattern, $replace, $text);
But there are no replacements. I know that my reg exp is wrong, but I canβt pinpoint where / why. Help?
** Edit: ... sample data on request?
$text = '@janesmith I like that, but my friend @johndoe said it better.';
Required Conclusion:
@janesmith I like it, but my friend @johndoe said better.
***** MY FULL FUNCTION *****
function linkify($string, $twitter=false) { // reg exp pattern $pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; // convert string URLs to active links $new_string = preg_replace($pattern, "<a href=\"\\0\">\\0</a>", $string); if ($twitter) { $pattern = '/@([a-zA-Z0-9_]+)/'; $replace = '<a href="http://twitter.com/\1">@\1</a>'; $new_string = preg_replace($pattern, $replace, $new_string); } return $new_string; }
source share