dongque1958 2010-11-23 23:29
浏览 20
已采纳

使用php在推文中围绕推特用户名包装html <a>标签

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!

  • 写回答

2条回答 默认 最新

  • duanbipu7601 2010-11-23 23:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口