note 79521 added to function.preg-match
| From: | vladimir at pixeltomorrow dot com | Date: | Sat, 01 Dec 2007 21:03:48 +0000 |
| Subject: | note 79521 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132718@lists.php.net to get a copy of this message | ||
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
----
Server IP: 193.95.141.37
Probable Submitter: 89.101.121.46
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/79521
Del: integrated -- https://master.php.net/note/delete/79521/integrated
Del: useless -- https://master.php.net/note/delete/79521/useless
Del: bad code -- https://master.php.net/note/delete/79521/bad+code
Del: spam -- https://master.php.net/note/delete/79521/spam
Del: non-english -- https://master.php.net/note/delete/79521/non-english
Del: in docs -- https://master.php.net/note/delete/79521/in+docs
Del: other reasons-- https://master.php.net/note/delete/79521
Reject -- https://master.php.net/note/reject/79521
Search -- https://master.php.net/manage/user-notes.php