正则表达式捕获提及

时间:2012-05-24 16:13:46

标签: php regex

我需要在没有RT的情况下匹配所有提及。我试过添加!否定rt但不起作用。

preg_match( '/\b!rt\s*@([a-zA-Z0-9_]{1,20})/i', $string, $data );

这必须匹配:'你好@user你好吗' 这不是:'RT @user你好吗'

我没有尝试提取用户名或其他内容,我需要知道文本是否有@user而不是RT。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

!在正则表达式中没有“否定”。这符合文字!。你想要的是一个“负面观察”。

/(?<!RT)\s@([a-z0-9]{1,20})/i

(?<!RT)表示“前面没有”RT“。

这将匹配用户名,“RT”不包含在匹配项中。

$match = preg_match('/(?<!RT)\s@([a-z0-9]{1,20})/i', $string);

如果$match0,则表示该字符串为“RT @user ...”。如果$match不是0,则表示字符串以“RT @user”开头。

DEMO:http://ideone.com/bOWbu

有关正则表达式外观的更多信息:http://www.regular-expressions.info/lookaround.html

答案 1 :(得分:0)

如果您只想匹配用户名,可以尝试/(?<!RT)(@.*?)(?=\s)/i

答案 2 :(得分:0)

我相信应该这样做:

$string1 = 'hello @user how are you';
preg_match('~\s?(?<!RT) @[a-z0-9]+~i', $string1, $data);
print_r($data);
// array('0' => '@user');

$string2 = 'RT @user how are you';
preg_match('~\s?(?<!RT) @[a-zA-Z0-9]+~', $string2, $data);
print_r($data);
// empty array