Is there a regular expression optimizer in PHP?
Perl has Regexp::Optimizer, is there anything similar in PHP? My searches haven't turned up anything.
For example, Regexp::Optimizer would turn
/foobar|fooxar|foozap/
into
/foo(?:[bx]ar|zap)/
Update: I wanted to keep that question really short so that people would not try to over-interpret it but it turns out it had the opposite effect. I am looking for something that takes a regular expression and outputs a functionally equivalent yet more efficient regular expression. I have found such a thing in Perl but none in PHP, and I am wondering whether such a thing exists. In that respect, I expect a y开发者_C百科es/no answer, accompagnied with a link if applicable. Thanks and sorry for the confusion.
no (afaik), but do the ctype functions for basic checking where people often use regex.
Since PCRE supports Perl syntax, just use the Perl module. There is an extension in PHP to instantly invoke Perl code. But you could just exec it and cache the result, unless you need a 'live' conversion:
$re = exec('perl -M"Regexp::Optimizer" -e 'print Regexp::Optimizer->new->optimize(qr'.escapeshellcmd($re).')';
You can pass the S option to the regex which will study it during the first compile(the regex is cached after that until the script dies)
http://php.net/manual/en/reference.pcre.pattern.modifiers.php
This is detailed fairly well in the PHP chapter in Mastering Regular Expressions Ed. 3 and in the particular example you give, it would optimize in a useful way.
Edit: Actually, after thinking about this a bit more, it wouldn't even need the S option, as PCRE will optimize that particular example on it's own. A better example would something that looks for just a few starting characters, like
/foobar|barfoo|helloworld/S
As it would then just look at items starting with [fbh]
So as it turns out, there is no generic regular expression optimizer for PHP as of December 1st, 2010.
精彩评论