Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing regex compilation errors

Tags:

regex

php

I am trying to set up a service similar to rubular, but with PHP as the language using the preg family of functions. It will take an input regex, a test string, and run preg_match().

How can I find out if a compilation error has occurred (eg: invalid regex), and if that is the case, what was the error? Normally it will throw warnings like:

Warning: preg_match() [function.preg-match]: Compilation failed: missing ) at offset x in ****** on line y

pcre_last_error() is totally useless here, since it will return 0 (PREG_NO_ERROR) if the regex fails to compile.

One option I am considering is to use output buffering to capture the warning, but there's got to be a better way.

like image 684
NullUserException Avatar asked Aug 21 '10 00:08

NullUserException


1 Answers

The best you can do is to omit the error message with @, check the return value and, if false, call error_get_last.

You could also write your own wrapper around pcre_compile. It receives pointers for storage of error codes and strings. Shouldn't be too difficult; preg_match is a thin wrapper.

like image 140
Artefacto Avatar answered Sep 20 '22 20:09

Artefacto