Ben Paton
Ben Paton

Reputation: 1442

Wrap link around links in tweets with php preg_replace

Hello I'm trying to display the latest tweet using the code below. This preg_replace works great for wrapping a link round twitter @usernames but doesn't work for web addresses in tweets. How do I get this code to wrap links around urls in tweets.

        <?php
        /** Script to pull in the latest tweet */
        $username='fairgroceruk';
        $format = 'json';
        $tweet = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
        $latestTweet = htmlentities($tweet[0]->text, ENT_QUOTES);
        $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
        $latestTweet = preg_replace('/http://([a-z0-9_]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); echo $latestTweet;

    ?>

Thanks for the help,

Ben

Upvotes: 1

Views: 1336

Answers (2)

Robert Abramski
Robert Abramski

Reputation: 36

I added a period and an escaped backslash so the whole link is recognized. With the code above, it was only reading the link up to the dot. As long as there is a space between your link and the rest of the text, this regex should work.

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

Upvotes: 1

Arantor
Arantor

Reputation: 597

Mostly because the regular expression isn't a valid one - there's a / in the middle of it.

Either change the delimiter to something else, like so, to stop the // in the middle colliding:

$latestTweet = preg_replace('~http://([a-z0-9_]+)~i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); echo $latestTweet;

Note that you don't explicitly have to use ~, but it's far less commonly used in regular expressions (at least in my experience) than / ends up being.

As an alternative, you can escape the // part:

$latestTweet = preg_replace('/http:\/\/([a-z0-9_]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); echo $latestTweet;

Upvotes: 0

Related Questions