更新regex以仅匹配单个单词中的大写字符


Update regex to only match capital characters in a single word

考虑以下内容:

$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);

此处的预期输出为:

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

然而,因为@fortunemagazine中有一个"rt",所以输出为:

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

我以为正则表达式中包含了这样的错误。它只能与RT完全匹配,RT可以位于字符串的开头:"RT@UserName",也可以位于字符串中间的某个位置:"…RT@UserName…",但始终使用大写字母,并且永远不是一个有效的"RT",后跟除空格和"@UserName"之外的任何其他字符,其中"UserName"可以是a-zA-Z_

我在正则表达式中干什么?

return preg_replace("/'bRT'b/", $tag, $tweet);

您在regex修饰符中添加i使其不区分大小写,将其删除以仅匹配大写RT。

preg_replace("/RT(?='s)/", $tag, $tweet);

http://ideone.com/P7dxm