如何在php中的字符串中进行字符串检查?

时间:2010-10-01 06:49:26

标签: php

有谁知道如何在字符串中进行字符串检查?

例如:

$variable = "Pensioner (other)";

如果我想检查$ variable是否包含“养老金领取者”这个词,我怎么能用PHP做呢?我在php中尝试了以下代码,但它始终返回false :(

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

4 个答案:

答案 0 :(得分:3)

在手册中,the example使用===进行比较。 The === operator还比较两个操作数的类型。要检查“不相等”,请使用!==。

您的搜索目标'养老金领取者'位于0位置,该函数返回0,等于假,因此if ($pos)始终失败。要更正这一点,您的代码应为:

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

答案 1 :(得分:2)

更新

您使用的是反向功能strripos,您需要使用stripos

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

这应该做:

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

使用strpos/stripos时,严格类型比较(!==非常重要。

答案 2 :(得分:1)

strripos及其兄弟姐妹的问题是他们返回找到的子字符串的位置。因此,如果您正在搜索的子字符串恰好位于开头,则返回0,这在布尔测试中为false。

使用:

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

答案 3 :(得分:1)

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

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

^适合我。请注意,strripos()不区分大小写。如果您希望它是区分大小写的搜索,请改用strrpos()

相关问题