【发布时间】:2013-04-11 23:45:38
【问题描述】:
在将代码放入我的网站时,我正在尝试将所有 @ 和 # 转换为链接。
我发现一些 Jquery 代码看起来使用正则表达式来搜索 @ 和 # 但我不确定如何使用 PHP 来完成同样的事情。
代码是:
at: function(tweet) {
return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
});
},
hash: function(tweet) {
return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
});
},
如果我有这样的事情:
@BobBarker is going to #blahblah and also @BillyBob
我需要搜索并执行以下操作:
<a target="_blank"
class="twtr-atreply"
href="http://twitter.com/intent/user?screen_name=BobBarker'">@BobBarker
</a>
<a target="_blank"
class="twtr-atreply"
href="http://twitter.com/intent/user?screen_name=BillyBob'">@BillyBob
</a>
哈希标签也是如此:
#blahblah
我需要搜索并执行以下操作:
<a target="_blank"
class="twtr-hashtag"
href="http://twitter.com/search?q=%23blahblah">#blahblah
</a>
任何帮助都会很棒!
更新
我整理了一些 PHP,它们可以很好地找到 @ 或 # 的 first 瞬间,但不会一直循环。我将如何为它设置一个循环?
$theTweet = "@BobBarker is going to #blahblah and also @BillyBob";
if (preg_match("/\B[@@]([a-zA-Z0-9_]{1,20})/", $theTweet, $matches)) {
$theTweet = str_replace($matches[0],'<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' . trim($matches[0]) . '"> ' . trim($matches[0]) . '</a> ',$theTweet);
echo $theTweet . '<br />';
}
if (preg_match("/(^|\s+)#(\w+)/", $theTweet, $matches)) {
$theTweet = str_replace($matches[0],'<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' . trim($matches[0]) . '"> ' . trim($matches[0]) . '</a> ',$theTweet);
echo $theTweet;
}
更新 #2
回答了我自己的问题:o)
【问题讨论】:
标签: php javascript twitter hashtag