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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里