【发布时间】:2011-05-16 10:32:39
【问题描述】:
我拼凑了下面的代码块,以帮助我在我的网站上显示来自我的 Twitter 帐户的最新推文。但是,它不太正常,你能帮我调试一下最后一点吗?我正在寻找 PHP 将其转换为 HTML,并在 Twitter 用户名和链接周围使用链接标签,并使用 preg_replace 进行链接。
如果你测试这个脚本,你会发现当它在推文中呈现标准链接时会出现问题,它会将结束 标记放在a 之后太早。我确信这相对容易修复,并且可能与转义字符或其他东西有关。
我的主要代码块:
<?php
/** Script to pull in the latest tweet */
$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('/http:\/\/([[a-z0-9_\.\-\+\&\!\#\~\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
$latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
echo $latestTweet;
?>
【问题讨论】:
-
思考:你能不能只用空格分割推文,然后将任何以“http://”开头的段转换为 URL?它比运行正则表达式便宜得多,更简单,而且我认为它同样适用于这个用例。
-
这听起来可行。我不确定如何做到这一点,尽管@usernames 也不是以“http://” 开头
标签: php twitter preg-replace tweets