PHP preg_match返回错误的索引
我试图使用PHP的PHP preg_match返回错误的索引,php,regex,Php,Regex,我试图使用PHP的preg\u match从字符串中提取特定单词的所有索引。以单词hello为例: $r = "/\b(hello)\b/u"; 假设我想在这个字符串中查找它: $s = 'hello. how are you, hello there. helloorona!'; 如果我使用preg\u OFFSET\u CAPTURE参数运行preg\u match,并传入一个名为$matches的数组 preg_match($r, $s, $matches, PREG_OFFSET_C
preg\u match
从字符串中提取特定单词的所有索引。以单词hello
为例:
$r = "/\b(hello)\b/u";
假设我想在这个字符串中查找它:
$s = 'hello. how are you, hello there. helloorona!';
如果我使用preg\u OFFSET\u CAPTURE
参数运行preg\u match
,并传入一个名为$matches的数组
preg_match($r, $s, $matches, PREG_OFFSET_CAPTURE);
我希望返回类似的内容(即忽略最后一个“Helloorona”短语):
但事实上,当我通过json_encode
或通过循环所有匹配项返回echo$matches
的值时,返回的值总是:
["hello", 0], ["hello", 0]
如果我在一个类似的字符串上运行它,那么
$s = 'how are you, hello there.';
答案是
["hello", 13]
这是正确的。在hello
上运行它,我得到三个索引,都是0
摘要
因此,似乎索引计数器总是返回第一个索引。这是预期的行为吗?如何获取实际索引?
preg\u match
匹配第一个匹配,然后停止。结果数组始终包含其0
索引中的整个匹配表达式,以及从1
开始的以下索引中的所有捕获组。例如:
preg_match('/foo (\w+)/', 'foo bar', $r)
$r
此处包含0=>'foo-bar',1=>'bar'
因此,在您的例子中,由于这个原因,您只看到第一个hello
两次
如果要匹配表达式的所有匹配项,请使用preg\u match\u all
第二个[“hello”,0]
不是字符串中的第二个hello,而是子组的匹配项
使用preg\u match\u all
可获得预期结果:
// note: sub group is not necessary
$r = "/\bhello\b/u";
$s = 'hello. how are you, hello there. helloorona!';
preg_match_all($r, $s, $matches, PREG_OFFSET_CAPTURE);
最后一个hello没有显示,因为您使用的是
\b
,这是单词边界,例如之前/之后的任何内容都不是单词字符,它将捕获它。是的,您说得对,我尝试使用preg\u match\u all
,但也没有得到我期望的结果-删除子组最终解决了问题。谢谢
// note: sub group is not necessary
$r = "/\bhello\b/u";
$s = 'hello. how are you, hello there. helloorona!';
preg_match_all($r, $s, $matches, PREG_OFFSET_CAPTURE);