I have a string like this: $str1 = "mod 1 + mode 2 + comp 1 + toto"
.
I would like to test if mod 1
is in $str1
. I used strpos
but this function doesn't help开发者_开发技巧.
strpos
returns the position of the occurrence in the string starting with 0 or false otherwise. Using just a boolean conversion like in the following is a common mistake:
$str1 = "mod 1 + mode 2 + comp 1 + toto";
if (strpos($str, "mod 1")) {
// found
}
Because in this case strpos
will return 0. But 0 converted to Boolean is false:
var_dump((bool) 0 === false); // bool(true)
So you need to use a strict comparison:
$str1 = "mod 1 + mode 2 + comp 1 + toto";
if (strpos($str, "mod 1") !== false) {
// found
}
This is also what the documentation advises:
Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the
===
operator for testing the return value of this function.
You can make use of the strstr function.
$str1 = "mod 1 + mode 2 + comp 1 + toto";
$str2 = "mod 1";
if(strstr($str1,$str2) !== false)
echo "Found $str2 in $str1\n";
if(stripos($str,'mod 1')!==false) $hasmod1 = true;
else $hasmod1 = false;
Care for the !==
this is the important part.
See http://php.net/manual/en/function.stripos.php
精彩评论