[英]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";
您正在使用反向函数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.