简体   繁体   中英

Wrap html <a> tag around a twitter username in a tweet with php

I want to wrap tags around the usernames in my tweets so that I can style them a differen't colour and link through to them. For example if this was my tweet:

@benpaton Lorem ipsum dolor sit amet, consectetur adipiscing elit.

I would like to do this:

<a href="http://www.twitter.com/benpaton" target="_blank" class="green">@benpaton</a> Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

This is the php I'm using at the moment to render my latest tweet at the moment currently with out links:

        <?php
        /** Script to pull in the latest tweet */
        $username='benpaton'; // set user name
        $format='json'; // set format
        $tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}")); // get tweets and decode them into a variable
        $latestTweet = $tweet[0]->text; // copy the text element from the latest tweet[0] to var $latestTweet
        $latestTweet = str_replace("\"","",$latestTweet);  // remove speech marks from tweets as this closes the alt tag
    ?>

Thanks for your help!

$latestTweet =
  preg_replace('/@(\w+)/',
               '<a href="http://www.twitter.com/$1" target="_blank" class="green">@$1</a>',
               $latestTweet);

Try this:

<?php

$username = 'benpaton';
$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" class="green">@$1</a>', $latestTweet);
echo $latestTweet;

?>

The preg_replace will handle the link writing, the htmlentities() will encode quotation marks so they should be able to be included in your output without breaking anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM