dpt1712 2012-02-15 09:48
浏览 54
已采纳

更新正则表达式仅匹配单个单词中的大写字符

Consider the following:

$tweet = "RT @forunemagazine Comment here RT @foo Blah";

function _process_retweets($tweet) {
  preg_match('/RT +@[^ :]+:?(.*)/ui', $tweet, $retweets);
  if (count($retweets) > 0) {
    $tag = ' {RT} '; // In reality, output could also be {RT|id}, etc. 
                     // but this is not relevant here
    return preg_replace("/RT/ui", $tag, $tweet);
  }
  else {
    return $tweet;
  }
}

echo _process_retweets($tweet);

The expected output here is:

{RT} @fortunemagazine Comment here {RT} @foo Blah

However, because there is a "rt" in @fortunemagazine, the output is:

{RT} @fo {RT} unemagazine Comment here {RT} @foo Blah

I thought the regex was covered for mistakes like this. It sould only match exactly RT, which could be at the beginning of the string: "RT @UserName" or in the middle somewhere: "... RT @UserName ..." but always in CAPITALS and never is a valid "RT" followed by any other character than a space and then a "@username", in which "username" can be a-zA-Z_

What am I doing wring in the regex?

  • 写回答

3条回答 默认 最新

  • dqpfkzu360216 2012-02-15 09:57
    关注
    return preg_replace("/\bRT\b/", $tag, $tweet);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序