为什么preg_match_all返回两个匹配?

时间:2014-10-28 10:57:40

标签: php regex preg-match-all duplicate-data

我试图识别一个字符串是否在使用preg_match_all的双引号之间有任何单词,但它是重复的结果,第一个结果有两组双引号,其中被搜索的字符串只有一套。

这是我的代码:

$str = 'Test start. "Test match this". Test end.';
$groups = array();
preg_match_all('/"([^"]+)"/', $str, $groups);
var_dump($groups);

var转储产生:

array(2) {
    [0]=>
    array(1) {
        [0]=>
        string(17) ""Test match this""
    }
    [1]=>
    array(1) {
        [0]=>
        string(15) "Test match this"
    }
}

正如您所看到的,第一个数组是错误的,为什么preg_match_all会返回这个?

4 个答案:

答案 0 :(得分:9)

它返回2个元素,因为:

元素0捕获整个匹配的字符串

元素1..N捕获专用匹配。

PS:另一种表达方式可能是

(?<=")[^"]+(?=")

会捕获完全相同但在这种情况下你不需要额外的捕获组。

演示:http://regex101.com/r/lF3kP7/1

答案 1 :(得分:5)

如果你使用的是print_r而不是vardump,你会看到更好的方式。

Array
(
    [0] => Array
        (
            [0] => "Test match this"
        )

    [1] => Array
        (
            [0] => Test match this
        )

)

第一个包含整个字符串,第二个是你的匹配。

答案 2 :(得分:1)

这是因为您正在使用组匹配。将括号从模式中删除,您将获得一个数组。像这样:

preg_match_all('/\"[^"]+\"/', $str, $groups);

答案 3 :(得分:0)

删除括号。 您可以将模式写为'/"[^"]+"/'