views:

59

answers:

4

I am writing a PHP script that accepts a regular expression pattern from the user which is used by preg_match(). How can I check that the pattern is valid?

+2  A: 

Just test it. preg_match() will return FALSE if the pattern is not valid.

Return values: preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

Lekensteyn
+3  A: 

According to the docs,

preg_match() returns FALSE if an error occurred.

the problem is that it will also throw a warning.

One way to deal with this is is to suppress the output of the error message, catch the return value, and output the error using error_get_last() if it was false.

Something like

$old_error = error_reporting(0); // Turn off error reporting

$match = preg_match(......);

if ($match === false) 
 {
   $error = error_get_last();
   echo $error["message"];
 }

error_reporting($old_error);  // Set error reporting to old level

You may not need the error reporting bit in a production environment - it depends on your setup.

Pekka
+1 For mentioning error message output suppression.
Gumbo
You know, it's not forbidden to use `@` :p
Artefacto
Should be `if ($match === false)`
webbiedave
@Artefacto true, but it looks so *ugly*! :) @webbiedave cheers, corrected.
Pekka
A: 
if (preg_match($regex, $variable)) {
    echo 'Valid';
}
else {
    echo 'InValid';
}
Alexander.Plutov
You must use preg_match(...)!==false to check it because it can return 0 if it's valid but does not match
mck89
You should be comparing to FALSE: `if (preg_match($regex, $variable) !== FALSE) {`. The pattern can be valid, with no matches. See [docs](http://nl2.php.net/manual/en/function.preg-match.php)
Lekensteyn
A: 

I thought I had seen a method for this in MRE; turns out it was one Friedl wrote himself. Here's the listing.

Alan Moore