Jump to content

[SOLVED] Sort of a unique problem


dbo

Recommended Posts

I'm writing some code that allows users to enter in a regex string and then calls preg_match. Using preg_match to validate a regex string before calling preg_match just seems weird to me, so what I'd like to do is error handle preg_match... is there a way I could emulate functionality thats like:

 

preg_match(..., ...) || return false;

 

See I don't want to stop executing the script at all, just want to treat that function breaking as false and report an error message. I'm sure I could pull it off with a try/catch but that's not something that would work in PHP4. Soooo what other suggestion do you guys have?

Link to comment
https://forums.phpfreaks.com/topic/67293-solved-sort-of-a-unique-problem/
Share on other sites

I'm not 100% sure what your looking for..

 

but if you wish to check if the regex was valid then maybe use preg_last_error,

 

example

<?php
$RegEx = "/\s/si";
$String = "testing";
$data = @preg_replace($RegEx, $String);

switch(preg_last_error())
{
case 0:
//no error
break;
case 1:
echo "PREG_INTERNAL_ERROR";
break;
case 2:
echo "PREG_BACKTRACK_LIMIT_ERROR";
break;
case 3:
echo "PREG_RECURSION_LIMIT_ERROR";
break;
case 4:
echo "PREG_BAD_UTF8_ERROR";
break;

}
?>

"preg_match() returns FALSE if an error occurred."

So,

if(preg_match(your input) === false){
print 'error';
}

 

You only use || inside a conditional statement, you don't just say do this or this. You say if this, do this, which can mean if this fails, do this. Same thing.

Take the following code for example:

 

    $matches = preg_match("/balh", "10");
    if( $matches != 0 ) echo "woot!";

 

Naturally ther errors out because I'm missing my closing / in the regex. However, it yields this error message:

 

Warning: preg_match() [function.preg-match]: No ending delimiter '/' found in /var/www/test.php on line 20. Are you suggesting that I compress the error message with @ and it will return false?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.