带有preg_match_all的正则表达式仅匹配第一次出现

时间:2013-10-31 14:33:26

标签: php regex

这个带有/\@[a-z0-9]+/i的正则表达式preg_match_all()只匹配@ a-z的首次出现?

在php中使用它:preg_match_all('/\@[a-z0-9]+/i', $input, $matches)

3 个答案:

答案 0 :(得分:1)

犯了简单的错误?

这匹配@的所有实例,后跟任何字符:a-zA-Z0-9(1次或更多次)。

此外,您无需在此处转义@

<?php

$text = <<<T
@fooo
@bar1234
@stackoverflow
T;

preg_match_all('/@[a-z0-9]+/i', $text, $matches);
print_r($matches);
?>

输出

Array
(
    [0] => Array
        (
            [0] => @fooo
            [1] => @bar1234
            [2] => @stackoverflow
        )
)

答案 1 :(得分:0)

它将匹配一个且仅匹配一个@,然后匹配一个或多个字母/数字(因为+)。

你的正则表达式对最后的i也不区分大小写。

所以它会匹配'@'','@ aaaAAAAzZZeeEErrRttT1234',但不是'@@ aaa'。

答案 2 :(得分:0)

你的正则表达式与preg_match_all结合使用是正确的。如果您不确定,请写一个小的测试脚本:

 <?php
 $input = '@a @b';
 preg_match_all('/\@[a-z0-9]+/i', $input, $matches);
 var_dump($matches);
 ?>

如果您想要更简单的正则表达式,可以使用/@\w+/