开发者

How to get the end position of a regex (PCRE) in PHP?

I using the matches optionnal parameter with PREG_OFFSET_CAPTURE flag. I get the start offset and the matching expression.... I don't find the options to get the end of the matching expression like in Java Regexes. Is there a 开发者_如何学Gosolution or my last resort is : offset + strlen(matching_string) ?


Just put a (.) at the end of your regex and take the captured offset of that ;)


You can match \G - that's the position of the regex engine after the previous match.

However, I don't find this any better than your "last resort" method. What's so bad about that?


If PHP is like Perl, there should be a couple of arrays of offsets for all the matches.

In Perl its @- and @+ .. Index 1 .. is capture group offsets. Index 0 is the total match offsets.

if ('012345678' =~ /4/ ) {
    print "Match start = $-[0], match end = $+[0]\n";
}

Prints Match start = 4, match end = 5


I had a similar problem but i could not use

 strlen(matching_string)

Cause matching string was a regex with variable amount characters.

Instead I used preg_replace the matching string and worked from there.

I guess it similar to @NikiC suggestion but it took me a while to figure out.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜