这是一些示例代码,用于用 php 中的链接替换链接、主题标签和 attags
$tweet = "@george check out http://www.google.co.uk #google";
//Convert urls to <a> links
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
//Convert hashtags to twitter searches in <a> links
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
//Convert attags to twitter profiles in <a> links
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
echo $tweet;
这给出了输出
<a href="http://www.twitter.com/george">@george</a> check out <a target="_blank" href="http://www.google.co.uk">http://www.google.co.uk</a> <a target="_new" href="http://twitter.com/search?q=google">#google</a>
所以你可以将你的代码更改为
function get_tweet() {
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'secret',
'consumer_secret' => 'secret',
'user_token' => 'secret',
'user_secret' => 'secret',
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'evanrichards',
'count' => '1'));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
$tweet = $tweets[0]['text'];
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
echo($tweet);
}
我确信正则表达式可以改进。
或者更好的是,您可以将其拆分为自己的功能。
function linkify_tweet($tweet) {
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
return $tweet;
}
function get_tweet() {
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'secret',
'consumer_secret' => 'secret',
'user_token' => 'secret',
'user_secret' => 'secret',
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'evanrichards',
'count' => '1'));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
echo(linkify_tweet($tweets[0]['text']));
}