繁体   English   中英

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

[英]how can I do a string check inside a string in php?

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

例如:

$variable = "Pensioner (other)";

如果我想检查$ variable是否包含单词'Pensioner',如何在PHP中做到这一点? 我已经在php中尝试了以下代码,但总是返回false :(

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

在手册中, 该示例使用===进行比较。 ===运算符还会比较两个操作数的类型。 要检查“不等于”,请使用!==。

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

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

更新:

您正在使用反向函数strripos ,需要使用stripos

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

应该这样做:

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

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

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

采用:

if ( $pos !== FALSE ) ...
$variable = 'Pensioner (other)';
$pos = strripos($variable, 'pensioner');

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

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

暂无
暂无

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

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