Ben*_*ton 2 php twitter preg-replace tweets
我拼凑了下面的代码块,以帮助我通过我的Twitter帐户在我的网站上显示最新的推文.但是,它不是很正常,你可以帮我调试最后一点.我正在寻找PHP将其转换为HTML,其中链接标签包含在Twitter用户名和正在使用的链接上preg_replace.
如果你测试这个脚本,你会发现它在推文中提取标准链接的时候会出现问题,它会在过早发布关闭的<a>标签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;
?>
Run Code Online (Sandbox Code Playgroud)
将正则表达式更改为:
$latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
Run Code Online (Sandbox Code Playgroud)
这对我有用.
完整代码
<?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;
?>
Run Code Online (Sandbox Code Playgroud)