I got a string $str = "颜色代码";
, I would like to check if this string contain "颜色"
. I've tried using the code below, but I keep getting false return.
mb_strpos($str, "颜色", 0 ,"GBK");
I got a string $str = "颜色代码";
, I would like to check if this string contain "颜色"
. I've tried using the code below, but I keep getting false return.
mb_strpos($str, "颜色", 0 ,"GBK");
Maybe you just have forgotten to check whether the value is integer:
if(mb_strpos($str, "颜色", 0 ,"GBK")===false)
echo "The value does not contain \"颜色\"\n";
else
echo "\"颜色\" is part of the string."
The three =
invoke a strict type comparison. Normally, false
equals 0
, but they are of different variable types - bool
and int
respectively.
In the documentation of strpos, which acts similarly, there's a big red warning:
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.
Try using utf8_decode
:
mb_strpos($str, utf8_decode("颜色"), 0 ,"GBK");
The code does work:
$str = "颜色代码";
$test = mb_strpos($str, "颜色", 0 ,"GBK");
echo $test;
But the problem you are facing is because the 颜色
strpos
returns 0
which is the correct string position but your code logic might misinterpret that as false
. To see what I mean take the 颜色
and place it at the end of the string like this:
$str = "代码颜色";
$test = mb_strpos($str, "颜色", 0 ,"GBK");
echo $test;
And the returned string position is 3 which is correct as well. A better approach to simply see if the 颜色
is in the string is to use preg_match
like this:
$str = "颜色代码";
$test = preg_match("/颜色/", $str);
echo $test;
And the output for that would be a boolean 1
which equates to true
which I believe is what you are looking for.
Beyond the functionality working as expected, there is a clear speed benefit to using preg_match
over mb_strpos
as shown here.
mb_strpos: 3.7908554077148E-5
preg_match: 1.1920928955078E-5
It’s more than 3x faster to use preg_match
when compared to mb_strpos
.