In the manual for preg_match, it says:

Note: Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as , $ or (?<=x).

<?php
$subject = "abcdef";
$pattern = '/def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

The above example will output:

Array
(
)

while this example
<?php
$subject = "abcdef";
$pattern = '/def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

will produce

Array
(
[0] => Array
(
[0] => def
[1] => 0
)

)

I'm having trouble seeing why the first option doesn't work, even though it says why at the top 😕 . If the offset begins at 3, the pattern should match, shouldn't it? It does say that the offset is specified in bytes. Is that the reason it won't match?

    Because you have a "start-of-string" anchor (the "") as part of the regex. The offset parameter tells the preg parser to start looking for matches at that position, but it does not ignore the beginning of the string. Therefore it knows that the "d" is not anchored to the beginning of the entire string, so it does not match. (Therefore, no simple regex like that which begins with a "" anchor will ever find a match if you use a non-zero offset, since only the first character of a string is so anchored.)

      Write a Reply...