strpos 不适用于逗号分隔字符串中的第一个字符串

strpos not working for first string among comma separated strings

看到这个demo

我有两个逗号分隔的字符串列表,想查找字符串和 return 一条消息。我注意到在我寻找第一个列表的第一个字符串的特定情况下,它不会找到它。如果我将该字符串移动到另一个位置,它会。不明白为什么。

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";

$search = "AZ";


if ( strpos($dynamic_list . ',' . $static_list, $search) == false && !empty($search) ) { // check string is not empty + that it is not on any of the lists
    echo 'not found: String '.$search.' was not found in lists';
} else {
    echo 'found';
}
    $dynamic_list = "AZ, CA, CO";
    $static_list = "MN,WA,IA";

    $search = "AZ";


    if ( strpos($dynamic_list . ',' . $static_list, $search) === false && !empty($search) ) { // check string is not empty + that it is not on any of the lists
        echo 'not found: String '.$search.' was not found in lists';
    } else {
        echo 'found';
    }

添加===然后尝试

You just need to replace === with ==, So it will check variable type to, here your strpos() is returning 0 which will read as false as in your if will get

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";
$search = "AZ";
if ( strpos($dynamic_list . ',' . $static_list, $search) === false && !empty($search) ) { 
        echo 'not found: String '.$search.' was not found in lists';
} else {
        echo 'found';
}

注意我们对 === 的使用。简单地 == 不会按预期工作,因为 'A' 在 'AZ' 中的位置是第 0 个(第一个)字符。所以 === 会完成这项工作 在这里为你。让我们试试 ===

查看示例: https://www.php.net/manual/en/function.strpos.php

警告

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.

<?php

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";
$search = "AZ";

if (strpos($dynamic_list . ',' . $static_list, $search) === false) {
    echo 'not found: String '.$search.' was not found in lists';
} else {
    echo 'found';
}

演示: https://3v4l.org/bo4Yjr