Reputation: 213
I'm doing some work with a Twitter feed and want to turn any hashtags into a clicable URL.
A hashtag is a hash symbol ('#') immediately followed by a word acting as a search tag - and contains no spaces.
An example would be ...
@Eutechnyx looking to form a tech group in #Shoreditch next year. Game and Web programmers get in touch. #AutoClubRev
There are two tags here, #Shoreditch and #AutoClubRev.
These should respectively become the following links ...
https://twitter.com/#!/search?q=%23Shoreditch and https://twitter.com/#!/search?q=%23AutoClubRev
I'm assuming I should be using preg_replace_callback here and not just vanilla preg_replace, as I am trying to take a backreference ($1) and change it not just display it. But of course I could be wrong. I'm not fuessed on which function to use - as long as it does the job and is relatively efficient.
Thanks, Pete
Upvotes: 0
Views: 550
Reputation: 27313
preg_replace
should be able to do it.
$test = "@Eutechnyx looking to form a tech group in #Shoreditch next year. Game and Web programmers get in touch. #AutoClubRev";
echo preg_replace('|#([\w_\d]+)|', '<a href="https://twitter.com/#!/search?q=%23\1">#\1</a>', $test);
Upvotes: 1