Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

php - How do I find the index of a regex match in a string?

In php, it's fairly simple to find and capture all substrings that match a given regex, but is there a simple way to find the index of the first regex match in a string?

i.e. I'd like something that operates like this:

$str = "123456789abcdefgh";
$index = preg_index("#abcd#", $str);
// $index == 9
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...