Wrap a tag around a link in a tweet using php

Hello I need to add an href tag around the tweet link in php, for example if I have a tweet like:

@username tweet body message http://t.co/sfr34s5


I need to turn it into this using php:

@username tweet body message <a href="http://t.co/sfr34s5">http://t.co/sfr34s5</a>


I think it can be done using preg_replace and I have something like this which already wraps the link around the twitter @usus name like below:

$tweet= preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $tweet);


How do I edit the regex part of this to put the tag around the URLs in the tweets that appear?


source to share

1 answer

Try using the following code:

$source = '@username tweet body message http://t.co/sfr34s5';
$pattern = '/(http:\/\/[a-z0-9\.\/]+)/i';
$replacement = '<a href="$1" target="_blank">$1</a>';

$source = preg_replace($pattern, $replacement, $source); 


The regular expression will match all lines starting with "http: //" followed by a sequence of alpha numeric values, forward slashes, or periods.

It should work in all cases, however if you're only trying to fetch t.co references, you can use this safer version of the template:

$pattern = '/(http:\/\/t\.co\/[a-z0-9]+)/i';


This will only match "http://t.co/ [alnum-chars].

You will need to change the template as per your requirement if you need to match all urls. For example. to match http://t.co/abcde?x=1&y=2 you need the following template:

$pattern = '/(http:\/\/[a-z0-9\.\/?=&]+)/i';


I tested this on PHP5.3 and it worked with the url you provided.



All Articles