为什么preg_match_all返回两个匹配?

问题描述 投票:3回答:3

我试图确定一个字符串是否在使用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会返回这个?

php regex preg-match-all duplicate-data
3个回答
5
投票

嗨,如果您使用的是print_r而不是vardump,您将会以更好的方式看到差异。

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

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

)

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


9
投票

它返回2个元素,因为:

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

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

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

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

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

但是:ぁzxswい


0
投票

删除括号。你可以把模式写成http://regex101.com/r/lF3kP7/1

© www.soinside.com 2019 - 2024. All rights reserved.