简体   繁体   English

搜索字符串时使用strpos失败

[英]No success by using strpos when searching a string

I have the following code/string: $ids="#222#,#333#,#555#"; 我有以下代码/字符串: $ids="#222#,#333#,#555#";

When I'm searching for a part using: 当我使用以下方式搜索零件时:

if(strpos($ids,"#222#"))

it won't find it. 它找不到。 But when I'm searching without the hashes, it works using: 但是,当我搜索没有哈希值时,它可以使用:

if(strpos($ids,"222"))

I've already tried using strval for the search parameter, but this won't work also. 我已经尝试过使用strval作为搜索参数,但是这也行不通。

strpos starts counting from 0, and returns false if nothing is found. strpos从0开始计数,如果未找到,则返回false。 You need to check if it's false with === like this... 您需要像这样用===检查它是否为假...

if (strpos($ids, '#222#') === false) // not found

Or use !== if you want the opposite test... 或使用!==如果您想要相反的测试...

if (strpos($ids, '#222#') !== false) // found

See the PHP Manual entry for more information 有关更多信息,请参见PHP手册条目

You are not explecitely testing for FALSE when using strpos. 使用strpos时,您并没有明确测试FALSE。 Use it like this: 像这样使用它:

if(strpos($string, '#222#') !== FALSE) {
    // found
} else {
    // not found
}

Explanation: You are using it like this: 说明:您正在像这样使用它:

if(strpos($string, '#222#')) {
    // found
}

What is the problem with this? 这是什么问题? Answer: strpos() will return the position in string where the substring was found. 答案: strpos()将返回在字符串中找到子字符串的位置。 In you case 0 as its at the beginning of the string. 在您的情况下, 0作为它在字符串开头的位置。 But 0 will be treated as false by PHP unless you issue an explicit check with === or !== . 但是,除非您使用===!==进行显式检查,否则PHP将0视为false。

It is working as expected. 它按预期工作。 strpos() returns 0 because the string you're searching for is at the beginning of the word. strpos()返回0,因为您要搜索的字符串在单词的开头。 You need to do an equality search: 您需要进行相等搜索:

Update your if() statement as follows: 如下更新您的if()语句:

if(strpos($ids, '#222') !== false)
{
    // string was found!
}

Try with this : 试试这个:

$ids="#222#,#333#,#555#";
if(strpos($ids,"#222#") !== false)
{
    echo "found";
}

You should use !== because the position of '#222#' is the 0th (first) character. 您应该使用!==因为'#222#'的位置是第0th (first)字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM