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);
This entry was posted in PHP, Tutorials and tagged Links, PHP, Regular Expression, Tutorial, Twitter. Bookmark the permalink.
Pingback: PHP regular expression Twitter links | PHP-Blog.com
Would this not be cleaner and faster:
preg_replace(“/@([A-Za-z0-9_]+) /”,”$0“,$twitter->text);
Pingback: PHP form validation | Papermashup.com
Thanks, found this extremely useful.
I need one regular expression for twitter trends links like #xxxx
Please help me!
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?
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
lol, ur comments ate my anchor tags
haha
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.
Follow us on Twitter and get in-stream messages
10 discussions around PHP regular expression Twitter links