加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 正则表达式有条件地用超链接替换Twitter标签

发布时间:2020-12-13 14:06:45 所属栏目:PHP教程 来源:网络整理
导读:我正在编写一个小型 PHP脚本,从用户资料夹中获取最新的十几个Twitter状态更新,并将其格式化以便在网页上显示.作为其中的一部分,我需要一个regex替换来重写hashtag作为search.twitter.com的超链接.最初我试图用: ?php$strTweet = preg_replace('/(^|s)#(w+
我正在编写一个小型 PHP脚本,从用户资料夹中获取最新的十几个Twitter状态更新,并将其格式化以便在网页上显示.作为其中的一部分,我需要一个regex替换来重写hashtag作为search.twitter.com的超链接.最初我试图用:
<?php
$strTweet = preg_replace('/(^|s)#(w+)/','1#<a href="http://search.twitter.com/search?q=%232">2</a>',$strTweet);
?>

(取自https://gist.github.com/445729)

在测试过程中,我发现#test被转换成Twitter网站上的一个链接,但是#123不是.经过一番互联网检查和各种标签之后,我得出的结论是,标题必须包含字母字符或其中的下划线,以构成一个链接;只有数字字符的标签才会被忽略(可能是停止像“好的演示文稿Bob,幻灯片3是我的最爱!”).这使得上述代码不正确,因为它将很乐意将#123转换为链接.

在一段时间里,我没有做过很多正则表达式,所以在我的生锈中,我想出了以下PHP解决方案:

<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test,#l33t and #8oo8s are.';

// Get all hashtags out into an array
if (preg_match_all('/(^|s)(#w+)/',$test,$arrHashtags) > 0) {
  foreach ($arrHashtags[2] as $strHashtag) {
    // Check each tag to see if there are letters or an underscore in there somewhere
    if (preg_match('/#d*[a-z_]+/i',$strHashtag)) {
      $test = str_replace($strHashtag,'<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag,1).'">'.$strHashtag.'</a>',$test);
    }
  }
}

echo $test;
?>

有用;但是它似乎相当长的时间.我的问题是,是否有一个单独的preg_replace类似于我从gist.github获得的,只有当它们不包含数字时,才有条件地将主题标签重写为超链接?

(^|s)#(w*[a-zA-Z_]+w*)

PHP

$strTweet = preg_replace('/(^|s)#(w*[a-zA-Z_]+w*)/','1#<a href="http://twitter.com/search?q=%232">2</a>',$strTweet);

该正则表达式表示#后跟0个或更多个字符[a-zA-Z0-9_],后跟一个字母字符或下划线(1个或更多),后跟0个或更多字符.

http://rubular.com/r/opNX6qC4sG< - 在这里测试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读