I have a need to detect whether a regular expression is valid, so that invalid ones can be gracefully rejected in a user interface. On Stack Overflow there is a clever abomination to do this with another regular expression, which I plan to strenuously avoid.
There is a much simpler approach of running a match and checking for errors, which returns the correct boolean result, but it would be interesting to get the failure reason/message as well:
// The error is that preg delimiters are missing
$testRegex = 'Location: (.+)';
// This bit is fine
$result = preg_match($testRegex, ''); // returns false i.e. failure
$valid = is_int($result); // false, i.e. the regex is invalid
// Returns PREG_NO_ERROR, which means no error occured
echo preg_last_error() . "\n";
If I run this I correctly get:
PHP Warning: preg_match(): Delimiter must not be alphanumeric or backslash in ... on line ...
However, the output of the error function is 0
, which is equal to PREG_NO_ERROR
. I would have thought this would return a non-zero error code -- and it would be even better if I can get my hands on a clean version of the warning message.
It is of course possible that this is not generally available (i.e. is just available to the PHP engine for the purposes of printing the warning). I am running 5.5.3-1ubuntu2.6 (cli)
.