Is there anyway to set "no backreference" as default in php regex?
I am aware that th开发者_如何学JAVAe regex engine moves significantly faster without having to keep track of backreferences. I am also aware that I can add a ?:
at the start of the inside of the brackets to prevent the regex engine from performing a backreference.
However is there anyway I can invert the behavior such that non-matching becomes the default behavior ?(rather like the U
flag)
Short answer: no.
PHP uses the PCRE library for parsing regular expressions.
PCRE uses an NFA-based parser which keeps track of backreferences. What you are describing is a DFA-based parser or a Thompson NFA.
I'm not a PHP developer, but the PCRE library does indeed come with a "DFA mode." Most Linux distros will come equipped with "pcretest." If you don't have it, it comes with the PCRE library.
In the CLI:
$ pcretest
re> /(foo)\1/
data> foofoo
0: foofoo
1: foo
Now if we run this with the "-dfa" flag:
$ pcretest -dfa
re> /(foo)\1/
data> foofoo
Error -16
You may also want to look into "possessive quantifiers" to prevent backtracking.
You can try to use PHP PECL RE2 http://pecl.php.net/package/re2
精彩评论