正则表达式模式 - 匹配以@开头的单词

时间:2013-11-11 20:18:08

标签: php regex replace preg-replace

我的移动应用程序就像移动平台上的论坛(WP7,Silverlight,.NET)。一个功能是通过编写“@”字符后跟用户名来标记其他用户。

在服务器端,PHP,我正在解析文本,以便它匹配标签并用更可读的字符串替换它们,例如[tag](display name)|(user id)[/tag],但这对我们的目的并不重要。

为了匹配标签,我用空格替换所有特殊字符,所以我可以像.... @name, ....一样阻止它。然后我删除了可能已创建上一个命令的所有多个空格。最后我将每个空格拆分,然后检查该单词是否以“@”字符开头。 这当然不是最好的方法,但这是我迄今为止所做的。有一个弱点,新的行字符使我的代码失败。例如:

Hello, this is my first line
since I go to second and then I tag
@Jonh
who is a good boy

在这种情况下,我将在下面写的代码失败。 其中$resp是要解析的文本。

if (strpos($resp,'@') !== false) {
    $new_str = preg_replace('/[^a-zA-Z0-9_ \@]/', ' ', $resp);
    $new_str = preg_replace('/\s+/', ' ', $new_str);

    foreach(explode(' ', $new_str) as $word)
    {
        if (strpos($word, '@') === 0) {
            //found my tag!                 
            }

        }   
    }
}

你建议做什么?

1 个答案:

答案 0 :(得分:2)

您应该能够立即将任何单词与@之前的@匹配,而不是使用正则表达式替换您不想匹配的所有内容。

$subject = "..blah.. @name, ..blah..@hello,blah";
$pattern = '/@\w+/';
preg_match_all($pattern, $subject, $matches);
print_r($matches);

输出:

Array ( [0] => Array ( [0] => @name [1] => @hello ) )

/@\w+/假设只有数字,字母和下划线(即\w匹配的内容)是有效匹配(即@ user123_xd),如果要包含例如-(破解有效匹配(例如@ user1a-12),然后$ pattern将是/@[\w-]+/