Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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?

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

$str = "123456789abcdefgh";
$index = preg_index("#abcd#", $str);
// $index == 9
like image 442
Daniel Beardsley Avatar asked Sep 18 '11 22:09

Daniel Beardsley


People also ask

Which method returns the index where Match Found?

The INDEX MATCH[1] Formula is the combination of two functions in Excel: INDEX[2] and MATCH[3]. =INDEX() returns the value of a cell in a table based on the column and row number. =MATCH() returns the position of a cell in a row or column.

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

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.

like image 180
Jon Avatar answered Oct 01 '22 20:10

Jon