gpt4 book ai didi

php - 为什么 preg_match_all 返回两个匹配项?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:56:37 26 4
gpt4 key购买 nike

我正在尝试使用 preg_match_all 来确定一个字符串是否在双引号之间有任何单词,但是它是重复的结果,第一个结果的两边都有两组双引号,其中作为被搜索的字符串只有一套。

这是我的代码:

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

然后 var dump 产生:

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

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

最佳答案

它返回 2 个元素,因为:

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

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

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

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

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

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

关于php - 为什么 preg_match_all 返回两个匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26606545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com