How can I determine if a given string is a valid value for PHP preg_match?

I am creating an admin user interface where the user can control the PCRE list lines that are passed to PHP preg_match at other points in my application.

Before storing user input for future use with preg_match , I would first like to verify that user input is a valid PCRE expression, otherwise an error is generated when passing it to preg_match .

What is the best way to check a given string to see if it is a valid PCRE in PHP?

+6
source share
1 answer

It is best to just pass the preg_match string 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 this does not work, you can 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(); 
+3
source

Source: https://habr.com/ru/post/909469/


All Articles