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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?