简体   繁体   English

PHP-strpos未检查第一个单词

[英]PHP - strpos didn't check first word

I'm trying to do some validation in PHP, and one of them is checking whether there is a specific word in the inputted string or not. 我正在尝试在PHP中进行一些验证,其中之一是检查输入的字符串中是否有特定的单词。 The problem is, my code seem to not working when I put the specified word first. 问题是,当我将指定的单词放在第一位时,我的代码似乎无法正常工作。

here's the code: 这是代码:

$word = "aa bb cc dd";
if(strpos($word, 'aa') == false)
{
    echo "wrong input";
}

but if I change the $word to either bb aa cc dd or bb cc dd aa , it works. 但是,如果我将$word更改为bb aa cc ddbb cc dd aa ,它会起作用。 I wonder how to fix this though. 我不知道如何解决这个问题。

strpos will return false if your string isn't there. 如果您的字符串不存在, strpos将返回false。 Otherwise, it returns the position of your string. 否则,它将返回字符串的位置。

In this case, 'aa' is at the start of the string, which means that it's at position 0; 在这种情况下,“ aa”位于字符串的开头,这意味着它位于位置0; and 0 evaluates to false. 和0的结果为false。

You need to do a boolean compare on the result: 您需要对结果进行布尔比较:

if(strpos($word, 'aa') === false)

That's because strpos returns the position of the word, in this case 0. 0 is falsey. 这是因为strpos返回单词的位置,在这种情况下为0。0为false。 == does not check for identical matches, === does. ==不会检查相同的匹配项, ===会检查。 So use a triple equals. 因此,请使用三重等于。

It's even in the docs . 甚至在docs中

strpos is returning 0, as 'aa' is the 0th character. strpos返回0,因为'aa'是第0个字符。 As 0 == false but does NOT === false (it is not boolean), you need to use === instead of == . 由于0 == false但不是=== false(它不是布尔值),因此您需要使用===而不是==

You should use the strict comparison operator, this will match against the same type, so using === will check if it's a Boolean: 您应该使用严格的比较运算符,它将与相同的类型匹配,因此使用===将检查它是否为布尔值:

if(strpos($word, 'aa') === false)
{
    echo "wrong input";
}

Using == is a loose comparison, anything can be stated true (apart from true , 1 , string ), eg 使用==是一个松散的比较,可以将任何内容声明为true(除了true1string ),例如

"false" == false    // true
"false" === false   // false

The reason why it's false because it's comparing a string against a Boolean which returns false. 之所以为假,是因为它将字符串与返回假的布尔值进行比较。

Because the position of aa is 0, which equals to false . 因为aa的位置是0,所以等于 false

You have to use: if(strpos($word, 'aa') === false) 您必须使用: if(strpos($word, 'aa') === false)

Add a space before search string and find more than 0 position 在搜索字符串前添加一个空格,并找到多个位置

if(strpos(" ".$word, 'aa') > 0)
{
    echo "Found it!";
}

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

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