I want to implement something like “editor for regular expressions”. It is for power users of my PHP application. The problem is, I need something like “reflection” for the regular expression (to be more precise, for any given regular expression) to find out how many subpatterns it contains. In Python, I simply type:
re.compile(regex).groups
How to implement that in PHP? It would be also nice to be able safely know, if the expression is even able to compile. In Python, there are exceptions raised and it’s easy to handle them. PHP shoots my application without any alerts, or produces some warnings/errors, which can’t be caught.
Thanks for any suggestions!
There’s no introspection for preg regular expressions – pcre has a function for this (pcre_fullinfo) but for some reason php devs didn’t bother to provide a glue for it. You might consider filing a feature request for that on bugs.php.net.
The only way to check a validity of a regexp is to compile it within a try-catch block, see How to check if a string is a valid PCRE? for an example.
That said, I don’t think it’s a good idea to allow users to execute arbitrary regular expressions on your server. A malicious or simply improperly written expression can eat up all memory quite quickly.