doudieheng5322 2010-11-25 02:31
浏览 16

使用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

  • 写回答

2条回答 默认 最新

  • dongyan6910 2010-11-25 02:35
    关注

    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;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败