Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a given string is a valid input to PHP's preg_match?

Tags:

php

pcre

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?

like image 286
Josh Avatar asked Feb 27 '12 17:02

Josh


1 Answers

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();
like image 73
David Souther Avatar answered Sep 28 '22 08:09

David Souther