[英]Wrap html <a> tag around a twitter username in a tweet with php
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. 我想在我的tweet中将标签包装在用户名周围,以便可以为它们设置不同的颜色并链接到它们。 For example if this was my tweet:
例如,如果这是我的推文:
@benpaton Lorem ipsum dolor sit amet, consectetur adipiscing elit. @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,目前正在使用链接呈现我的最新推文:
<?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! 谢谢你的帮助!
$latestTweet =
preg_replace('/@(\w+)/',
'<a href="http://www.twitter.com/$1" target="_blank" class="green">@$1</a>',
$latestTweet);
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. preg_replace将处理链接编写,htmlentities()将对引号进行编码,因此它们应该能够包含在您的输出中而不会破坏任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.