preg_match随机行为

I have, among others, these strings: "boards/", "localhost", "mysql", "0", "1", "Testing Board", "PLAIN".

I receive them as post data from a form. Some of these can have multibyte chars, but none of the test strings used has multibyte chars.

I run them through if (!preg_match('/^./u', $str)).

That if check mostly evaluates to false, ie the preg_match returns 1. But sometimes it evaluates to true, ie 0 from that preg_match.

The true (0) seems to come totally random. But if one of the strings evaluates to true then they all do. It's either all or none.

Do anybody have some sort of explanation to that seemingly random behavior? And maybe a solution to fix it?

Cheers Jari

Have a look at the warning in the docs. http://php.net/manual/en/function.preg-match.php

Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

When you are running the preg_match on values as 0 and 1 it will return that match. Which will cause an evaluation to true when not handled correctly.

1 == true   //true
1 === true  //false
0 == false  //true
0 === false //false
1 == false  //false
1 === false //false
0 == true   //false
0 === true  //false