开发者

How do I find the index of a regex match in a string?

开发者 https://www.devze.com 2023-04-05 13:21 出处:网络
In php, it\'s fairly simple to find and capture all subst开发者_高级运维rings that match a given regex, but is there a simple way to find the index of the first regex match in a string?

In php, it's fairly simple to find and capture all subst开发者_高级运维rings that match a given regex, but is there a simple way to find the index of the first regex match in a string?

i.e. I'd like something that operates like this:

$str = "123456789abcdefgh";
$index = preg_index("#abcd#", $str);
// $index == 9


Use the PREG_OFFSET_CAPTURE flag with preg_match:

$str = "123456789abcdefgh";
$index = -1;
if(preg_match("#abcd#", $str, $matches, PREG_OFFSET_CAPTURE)) {
    $index = $matches[0][1];
}

The [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.

Edit: Added an if to make the code more presentable, it now doesn't take for granted that the pattern will definitely match.

See it in action.

0

精彩评论

暂无评论...
验证码 换一张
取 消