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

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


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.

Tags:

Php

String

Regex