Mix preg_match, binding and offset
I have $string = "hello world, world!";
, and I only need to match the first one world
, so I have too much offset. It starts with the 6th character. preg_match()
takes five arguments: pattern string, subject string , link array matching, int flags, and int offset .
My template: $pattern = "/^world/";
If I do preg_match($pattern, $string, $string_match, 0, 6)
, basically I expect it to work because the "anchor" will check the 6th letter of my string, because I am setting the offset. BUT NOT! This does not work. ABOUT!
A simple fix , rather than set an offset to a function preg_match()
, I use substr()
above $string
, for example preg_match($pattern, substr($string, 6), $string_match)
.
Is it possible to fix my first code to use the offset anchor correctly with preg_match()
? Or is it a unique solution?
source to share
You are using the wrong anchor; to play with a good offset, you need the \G
last anchor of the position position:
$string = 'hello world, world!';
var_dump(preg_match('/\Gworld/', $string, $matches, 0, 6)); // int(1)
Interestingly, the documentation states that it is \G
not supported, but this is certainly supported since 4.3.3.
source to share