问题
I'm trying to check if a specific character is not present in a string in my code and apparently php doesn't care about anything and always gets inside the if
foreach($inserted as $letter)
{
if(strpos($word, $letter) !== true) //if $letter not in $word
{
echo "$word , $letter, ";
$lives--;
}
}
In this case $word is "abc" and $letter is "b", I've tried changing a lot of random things like from true to false and things like that but I can't get it, can anyone help me please?
回答1:
Changing the way you validate should fix it, like below:
foreach($inserted as $letter)
{
//strpos returns false if the needle wasn't found
if(strpos($word, $letter) === false)
{
echo "$word , $letter, ";
$lives--;
}
}
回答2:
if(strpos($word, $letter) === false) //if $letter not in $word
{
echo "$word , $letter, ";
$lives--;
}
also, be careful to check explicitly against false
, strpos can return 0
(a falsey value) if the match is in the 0th index of the string...
for example
if (!strpos('word', 'w') {
echo 'w is not in word';
}
would output the, possibly confusing, message 'w is not in word'
来源:https://stackoverflow.com/questions/54095138/phps-strpos-not-working-and-always-getting-into-the-if-condition