regex - PHP preg_match returning the wrong indexes -
i'm trying extract indexes of specific word string using php's preg_match
. take example word hello
:
$r = "/\b(hello)\b/u";
let's want in string:
$s = 'hello. how you, hello there. helloorona!';
if run preg_match
preg_offset_capture
parameter , passing in array called $matches,
preg_match($r, $s, $matches, preg_offset_capture);
i expect returned (i.e. ignoring last "hellooroona" phrase):
["hello", 0], ["hello", 20]
but in fact, when return echo value of $matches
either through json_encode
or looping on matches, value returned always:
["hello", 0], ["hello", 0]
if run on similar string, let's
$s = 'how you, hello there.';
the answer
["hello", 13]
which correct. run on hello hello hello
, 3 indexes, 0.
summary
so seems index counter returning first index. expected behavior? how actual indexes?
the second ["hello", 0]
not second hello in string, match of sub group.
use preg_match_all
give expected result:
// note: sub group not necessary $r = "/\bhello\b/u"; $s = 'hello. how you, hello there. helloorona!'; preg_match_all($r, $s, $matches, preg_offset_capture);
Comments
Post a Comment