note 79521 deleted from function.preg-match by felipe
| From: | felipe@php.net | Date: | Sun, 23 Mar 2008 22:56:00 +0000 |
| Subject: | note 79521 deleted from function.preg-match by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137376@lists.php.net to get a copy of this message | ||
Note Submitter: vladimir at pixeltomorrow dot com
----
Here's a nice workaround to check if your regex is valid.
Sometimes PHP may throw an error like:
Warning: preg_match() [function.preg-match]: Unknown modifier '$' in foo.php on line 2
You can't really tell if the 'false' value is actually a value returned because the
rule isn't value, or because you regex rule doesn't really match your string.
To find out what is the deal with your regex rule (maybe you're building it on fly, etc), you
can find out if the "false" returned result is really coming because the string
doesn't match, or because a warning was issued.
For the last part, I like to use try... catch expressions, so it's highly recommended,
let's have a look:
<?php
function testMyRule($rule, $string) {
// don't forget to enable warning reporting if disabled
try {
/*
catch the preg match output warning, inside buffer
*/
ob_start(); // start bufffer
$result = serialize(preg_match($rule, $string));
$pwarnings = ob_get_contents(); // get results, including the warning if any
ob_end_clean(); // clean output
if (strpos($pwarnings, 'Warning')) { // is warning?
throw new Exception($pwarnings);
}
return unserialize($result); //
} catch(Exception $e) {
echo $e->getMessage();
die();
}
} // end of function
?>
Now, you have to make sure error reporting will allow warnings, and next, we'll serialize the
result of your preg_match function applied against your string.
If this issues a warning, we catch inside the buffer, and later see if the buffer contains the
warning.
We're serializing/unserializing the result of our pregmatch, because if we wouldn't
serialize it, it would come back as a string, instead of boolean.
Enjoy!
Vladimir Ghetau