You should try to match the regular expression against NULL
. If the result is FALSE (=== FALSE
), there was an error.
In PHP >= 5.5, you can use the following to automatically get the built-in error message, without needing to define your own function to get it:
// For PHP >= 8, use the built-in str_ends_with() instead of this function.
// Taken from https://www.php.net/manual/en/function.str-ends-with.php#126551
if (!function_exists('str_ends_with')) {
function str_ends_with(string $haystack, string $needle): bool {
$needle_len = strlen($needle);
return ($needle_len === 0 || 0 === substr_compare($haystack, $needle, - $needle_len));
}
}
function test_regex($regex) {
preg_match($regex, NULL);
$constants = get_defined_constants(true)['pcre'];
foreach ($constants as $key => $value) {
if (!str_ends_with($key, '_ERROR')) {
unset($constants[$key]);
}
}
return array_flip($constants)[preg_last_error()];
}
Attempt This Online
Note that the call to preg_match()
will still throw a warning for invalid regular expressions. The warning can be caught with a custom error handler using set_error_handler()
.
See Can I try/catch a warning?.