【问题标题】:Wrap link around links in tweets with php preg_replace使用 php preg_replace 将链接环绕在推文中的链接
【发布时间】:2012-08-03 06:17:36
【问题描述】:

您好,我正在尝试使用下面的代码显示最新的推文。这个 preg_replace 非常适合将链接包裹在 twitter @usernames 周围,但不适用于推文中的网址。如何获取此代码以将链接包装在推文中的 url 周围。

        <?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;

    ?>

感谢您的帮助,

【问题讨论】:

    标签: php twitter preg-replace


    【解决方案1】:

    我添加了一个句点和一个转义的反斜杠,以便识别整个链接。使用上面的代码,它只读取到点的链接。只要您的链接和文本的其余部分之间有空格,这个正则表达式就可以工作。

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

    【讨论】:

      【解决方案2】:

      主要是因为正则表达式不是一个有效的 - 中间有一个 /。

      要么将分隔符更改为其他内容,就像这样,以阻止中间的 // 碰撞:

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

      请注意,您不必明确使用 ~,但它在正则表达式中的使用(至少根据我的经验)远不如 / 最终使用。

      作为替代方案,您可以转义 // 部分:

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

      【讨论】:

      • 嗯,知道什么是它不起作用总是有用的,而不是“它不起作用”。我刚刚测试了第一个,并意识到原来的正则表达式实际上被破坏了——不是因为 / 转义,而是因为 URL 中可以包含更多字符。 [ ] 位至少需要: ([a-z0-9_\.\-\+\&\!\#\~\,]+) - 这仍然不是所有合法的 URL 字符,只是它们中的一个很好的子集。
      • 抱歉,这很难解释,但问题似乎是,如果你在 url 中有一个@twitterUsername,那么第一个 preg_replace 会被转义两次,最后会被第二个 preg_replace 弄得一团糟
      • 那为什么不把第二个替换移到另一个上面来解决这个问题呢?
      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      相关资源
      最近更新 更多