Preg_match_all conundrum.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Wolf_22
Forum Contributor
Posts: 159
Joined: Fri Dec 26, 2008 9:43 pm

Preg_match_all conundrum.

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Preg_match_all conundrum.

Post 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 />';
}
Wolf_22
Forum Contributor
Posts: 159
Joined: Fri Dec 26, 2008 9:43 pm

Re: Preg_match_all conundrum.

Post 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.
Post Reply