开发者

how can I do a string check inside a string in php?

Does anyone know how can I do a string check inside a string?

for example:

$variable = "Pensioner (other)";

If I want to check whether $variable contain the word 'Pensioner', how can I do it in PHP? I have tried the following code in php, but it's always return me false :(

$pos = strripos($variable,"Pensioner");
if($pos) echo 开发者_运维知识库"found one";
else echo "not found";


In the manual, the example uses a === for comparison. The === operator also compares the type of both operands. To check for 'not equal', use !==.

Your search target 'Pensioner' is at position 0, and the function returns 0, which equal false, hence if ($pos) failed all the time. To correct that, your code should read:

$pos = strripos($variable,"Pensioner");
if($pos !== false) echo "found one";
      else echo "not found";


Update:

You are using the reverse function strripos, you need to use stripos.

if (stripos($variable, "Pensioner") !== FALSE){
  // found
}
else{
 // not found
}

This should do:

if (strripos($variable, "Pensioner") !== FALSE){
  // found
}
else{
 // not found
}

The strict type comparison (!==) is important there when using strpos/stripos.


The problem with strripos and its siblings is that they return the position of the substring found. So if the substring you're searching happens to be at the start, it returns 0 which in a boolean test is false.

Use:

if ( $pos !== FALSE ) ...


$variable = 'Pensioner (other)';
$pos = strripos($variable, 'pensioner');

if ($pos !== FALSE) {
 echo 'found one';
} else {
 echo 'not found';
}

^ Works for me. Note that strripos() is case insensitive. If you wanted it to be a case-sensitive search, use strrpos() instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜