PHP regular expression Twitter links

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 , , , , . Bookmark the permalink.
Comments
10 discussions around PHP regular expression Twitter links
  1. Pingback: PHP regular expression Twitter links | PHP-Blog.com

  2. Jamie Bicknell says:

    Would this not be cleaner and faster:

    preg_replace(“/@([A-Za-z0-9_]+) /”,”$0“,$twitter->text);

  3. Pingback: PHP form validation | Papermashup.com

  4. Harry says:

    Thanks, found this extremely useful.

  5. kik3 says:

    I need one regular expression for twitter trends links like #xxxx

    Please help me!

  6. Okay, it broke my submitted HTML code… Another try to comment… ;)

    This regex will destroy your HTML code if you have something like this:

    <a href=”http://www.example.com” title=”Bla @test blubb”>Don\’t break!</a>

  7. Ashley says:

    @Dominik As the title of the tutorial explains. This Regular expression is for use with the Twitter API, It is not designed to be used with normal text with HTML in it. There is no reason for a user to type HTML code into Twitter as it will be automatically stripped out.

  8. André Lima says:

    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?

  9. muxcmux says:

    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

  10. muxcmux says:

    lol, ur comments ate my anchor tags :D haha

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribers
1,250
Twitter
510
Comments
1,207
Posts
125