I need to replace all words starting with @ in a text with the corresponding link to that twitter account. Right now I’m using something like this:
$tweet_text = preg_replace('/(@\w+)/', '<a href=\'#\'>\1</a>', $string);
That works, but the link goes nowhere. I’ve decided to use a combination of strpos() and substr() to get the actual word and then be able to link to that twitter account, but I was wondering if there’s a better solution. Any ideas?
Examples:
Before replacement:
'Imperfection is the new perfection... RT @xHausOfCandy: @katyperry i think your bottom teeth and your wonk eye make you even more adorable.'
After replacement:
'Imperfection is the new perfection... RT <a href=''#''>@xHausOfCandy</a>: <a href=''#''>@katyperry</a> i think your bottom teeth and your wonk eye make you even more adorable.'
Desired:
'Imperfection is the new perfection... RT <a href=''http://twitter.com/xHausOfCandy''>@xHausOfCandy</a>: <a href=''http://twitter.com/katyperry''>@katyperry</a> i think your bottom teeth and your wonk eye make you even more adorable.'
Hope it’s more clear now!
Have the name in it’s own capture group and use \2 when referring to it in the replacement.