2013-Apr-15 - PHP Booleans bit me - preg_matchΒΆ

Do you see anything wrong with this piece of code?

if(preg_match($pattern, $string) !== 0)
{.. do our business... }

Well, it has a silly mistake that just wasted hours of my day today, so I thought I would share.

The main issue is that preg_match retuns 0 when it fails to match on a pattern and 1 when it does find it. Very simple.

However, on the code, instead of checking for equal to 1 to determine if it matched, I checked for anything not 0. Make sense?

Well, the main issue is that preg_match also returns FALSE on an error. So when an odd case caused the pattern to be invalid, it would actually match. It would check if FALSE !== 0, which is true. The fix? Just changed it to:

if(preg_match($pattern, $string) == 1)
{.. do our business... }

Silly me.

By Daniel B. Cid - Tags: dev - Notes index.

Quick Links


External Projects