在php中如何在字符串内部执行字符串检查?

在php中如何在字符串内部执行字符串检查?,php,Php,有人知道如何在字符串中进行字符串检查吗 例如: $variable = "Pensioner (other)"; 如果我想检查$variable是否包含单词“Pensioner”,如何在PHP中执行?我在php中尝试了以下代码,但总是返回false:( 更新: 您使用的是反转功能strripos,需要使用stripos if (stripos($variable, "Pensioner") !== FALSE){ // found } else{ // not fou

有人知道如何在字符串中进行字符串检查吗

例如:

$variable = "Pensioner (other)";
如果我想检查$variable是否包含单词“Pensioner”,如何在PHP中执行?我在php中尝试了以下代码,但总是返回false:(

更新: 您使用的是反转功能
strripos
,需要使用
stripos

if (stripos($variable, "Pensioner") !== FALSE){
  // found
}
else{
 // not found
}
这应该做到:

if (strripos($variable, "Pensioner") !== FALSE){
  // found
}
else{
 // not found
}
严格类型比较(
!=
在使用时非常重要。

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

您的搜索目标“Pensioner”位于位置0,函数返回0,等于false,因此如果($pos)始终失败,则返回
。要更正此问题,您的代码应为:

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

strripos及其同级的问题在于,它们返回找到的子字符串的位置。因此,如果您正在搜索的子字符串恰好位于开始位置,则它返回0,而在布尔测试中,该值为false

使用:


^对我有效。请注意,
stripos()
不区分大小写。如果您希望它是区分大小写的搜索,请使用
stripos()

是的,我确实尝试过使用您提供的代码,但结果仍然相同,它不会向我显示正确答案
$pos = strripos($variable,"Pensioner");
if($pos !== false) echo "found one";
      else echo "not found";
if ( $pos !== FALSE ) ...
$variable = 'Pensioner (other)';
$pos = strripos($variable, 'pensioner');

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