Hello I need to add an a href tag around a link in a tweet in php for example if I have tweet like this:
@username tweet body message http://t.co/sfr34s5
I need to turn this into this with php:
@username tweet body message <a href="http://t.co/sfr34s5">http://t.co/sfr34s5</a>
I think this can be done using preg_replace and I have something similar which already wraps a link around the twitter @username as 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 an a tag around the urls in tweets that appear?
Try the following code:
The regular expression will match all the strings that start with 'http://' and are followed by a sequence of alpha-numeric values, forward slashes or dots.
It should work in all cases, however, if you are only trying to extract t.co links you could use this safer version of the pattern:
This will only match 'http://t.co/[alnum-chars].
You will have to modify the pattern to your requirements if you need to match all URLs. E.g. to match http://t.co/abcde?x=1&y=2 you would need to use the following pattern:
I tested this on PHP5.3 and it worked with the URL you specified.