Here’s a quick piece of code to highlight replies to users in twitter for example @ashleyford this script uses regular expression to find and replace a based on two things. Firstly it checks for a space before the @ symbol and then checks for the space at the end of the users name, it then takes that string and replaces it with a link to the user twitter profile. Useful if you have a dynamic list of tweets that you want to linkify. All you need to do is change $ret to the variable the contains your string.
$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", $ret);
These two lines of code do a similar job with regards the structure however they look for the http:// and www. to determine a link.
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise", "'\\1<a href=\"\\2\" >\\2</a>'", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://\\2\" >\\2</a>'", $ret);
lol, ur comments ate my anchor tags
haha
Easier solution for both trends (#) and users (@)
preg_replace(‘/#(\w+)/’, ‘#\1‘, $text)
Just swap the # with a @ if you want to link to users ![]()
Cheers
When the @user is near a dot it includes the dot in the link. Ex: This is a test of @CocaCola. (result: Sorry, that page doesn’t exist!) Can you fix that?
I need one regular expression for twitter trends links like #xxxx
Please help me!
Thanks, found this extremely useful.
Pingback: PHP form validation | Papermashup.com
Would this not be cleaner and faster:
preg_replace(“/@([A-Za-z0-9_]+) /”,”$0“,$twitter->text);
Pingback: PHP regular expression Twitter links | PHP-Blog.com
Designer and web developer, Co-founder and Technical Director at Harkable.com London. Previously I worked at InMobi, Spotify and MySpace. Interests include photography and making short videos. Also an avid F1 fan.
Follow us on Twitter and get in-stream updates.
Subscribe to all the Papermashup tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
10 discussions around PHP regular expression Twitter links