PHP regular expression Twitter links

16 January 2009| 8 Comments| Print

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);

Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

8 Comments

  • Jamie Bicknell

    Would this not be cleaner and faster:

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

  • PHP form validation | Papermashup.com

    [...] Of course if you don’t have PHP 5 installed on your server you will have to use regex, i have a simple tutorial on how to use Regular expression with twitter here [...]

  • Harry

    Thanks, found this extremely useful.

  • kik3

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

    Please help me!

  • Dominik Deobald

    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>

  • Ashley

    @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.

  • André Lima

    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?

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

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

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here