Page 1 of 1

Preg_match_all conundrum.

Posted: Fri Dec 26, 2008 9:56 pm
by Wolf_22
The PHP manual states that preg_match_all will return the number of full pattern matches (which might be zero), or FALSE if an error occurred. In my pattern variable, I have '#foo#'. The input string I'm searching through ($in) is "1234 4332 foxo". Below is my conditional code where $m = matches and $filter = preg_match_all($p, $in, $m):

Code: Select all

 
    if(0 !== $filter){//if a match is found...
        echo 'A match has been found.<br />';
    }elseif(FALSE == $filter){//if error occurs...
        echo 'An error has been found.<br />';
    }else{//if good filter...
        echo 'Good filter.';
    }
Is it necessary to have a condition setup for the ERROR possibility or what? I keep tripping this when I don't even have "foo" within the input string and I can't seem to understand why... Also, I tried to make the first conditional be "if(FALSE !== $filter && $m > 0)", and it didn't work. Why?

Any input is appreciated.

Re: Preg_match_all conundrum.

Posted: Sat Dec 27, 2008 12:09 am
by requinix
If you're triggering the error condition then there's an error and you should fix it ;)

$filter is the number zero, yes? Because there weren't any matches. However, PHP considers zero and FALSE to be very similar values, so

Code: Select all

false == 0
is true - so you see the error message.

You can tell it to be precise with the comparison by using three =s, much like you did in the first condition. Normally I check for errors first, so my version of your code is

Code: Select all

if(false === $filter) {//if error occurs
   echo 'An error has been found.<br />';
}elseif(0 == $filter) {//no matches
    echo 'No matches.<br />';
}else{//matches
    echo 'A match has been found.<br />';
}

Re: Preg_match_all conundrum.

Posted: Sat Dec 27, 2008 12:35 am
by Wolf_22
I spent so many days messing around with that and the success of my efforts boiled down to a single, missing equals sign.

:banghead:

Ouch... Ouch... Ouch...

Hehe. Thanks tasairis. You just taught me how exactly and when to use the identical operator.