I am building an admin UI where a user can manage a list PCRE strings which get passed to PHP's preg_match
at other points in my application.
Before storing the user's input for later use by preg_match
, I'd first like to validate that the user's input is a valid PCRE expression, otherwise later on passing it to preg_match
throws an error.
What's the best way to validate a given string to see if it's a valid PCRE in PHP?
Your best bet will be to just pass the string to preg_match, and catch any errors that happen.
try{
preg_match($in_regex, $string, $results);
//Use $results
} catch (Exception $e) {
echo "Sorry, bad regex (/" . $in_regex . "/)";
}
[Edit] Since that won't work, you could try:
function bad_regex($errno, $errstr, $errfile, $errline){
echo "Sorry, bad regex.";
}
set_error_handler("bad_regex");
preg_match($in_regex, $string, $results);
restore_error_handler();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With