如何在字符串中找到正则表达式匹配的索引? [英] How do I find the index of a regex match in a string?
问题描述
在php中,查找和捕获与给定正则表达式匹配的所有子字符串是相当简单的,但是有没有一种简单的方法来查找字符串中第一个正则表达式匹配项的索引?
In php, it's fairly simple to find and capture all substrings that match a given regex, but is there a simple way to find the index of the first regex match in a string?
即我想要这样的东西:
$str = "123456789abcdefgh";
$index = preg_index("#abcd#", $str);
// $index == 9
推荐答案
将 上面的 The :添加了 Added an 查看实际效果 . See it in action. 这篇关于如何在字符串中找到正则表达式匹配的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!PREG_OFFSET_CAPTURE
标志与
[0]
对应于您要为其索引的正则表达式内的捕获组(整个表达式为0
,如果存在第一个捕获组,则为1
,等等),而[1]
是一个记录的固定索引.[0]
above corresponds to the capture group inside the regex whose index you want (0
for the whole expression, 1
for the first capturing group if it exists, etc) while the [1]
is a fixed index, as documented.if
以使代码更易于呈现,现在并不需要理会模式一定会匹配.if
to make the code more presentable, it now doesn't take for granted that the pattern will definitely match.