Home » Php » php – How to get the position of a Regex match in a string?

php – How to get the position of a Regex match in a string?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I know how to use preg_match and preg_match_all to find the actual matches of regex patterns in a given string, but the function that I am writing not only needs the text of the matches, but to be able to traverse the string AROUND the matches…

Therefore, I need to know the position of the match in the string, based on a regex pattern.

I can’t seem to find a function similar to strpos() that allows regex…any ideas?

How to&Answers:

You can use the flag PREG_OFFSET_CAPTURE for that:

preg_match('/bar/', 'Foobar', $matches, PREG_OFFSET_CAPTURE);
var_export($matches);

Result is:

array (
  0 => 
  array (
    0 => 'bar',
    1 => 3,     // <-- the string offset of the match
  ),
)

In a previous version, this answer included a capture group in the regular expression (preg_match('/(bar)/', ...)). As evident in the first few comments, this was confusing to some and has since been edited out by @Mikkel. Please ignore these comments.

Answer:

preg_match has an optional flag, PREG_OFFSET_CAPTURE, that records the string position of the match’s occurence in the original ‘haystack’. See the ‘flags’ section: http://php.net/preg_match

Answer:

With use of PREG_OFFSET_CAPTURE on preg_match() you will get number of times on matches on pattern. When there is a match this will have the offset value which starts from 0.

Using this value you can call preg_match again using offset parameter.