Use the PREG_OFFSET_CAPTURE
flag with preg_match
:
$str = "123456789abcdefgh";
$index = -1;
if(preg_match("#abcd#", $str, $matches, PREG_OFFSET_CAPTURE)) {
$index = $matches[0][1];
}
The [0]
above corresponds to the capture group inside the regex whose index you want (0
for the whole expression, 1
for the first capturing group if it exists, etc) while the [1]
is a fixed index, as documented.
Edit: Added an if
to make the code more presentable, it now doesn't take for granted that the pattern will definitely match.
See it in action.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…