在字符串中搜索字符串(但忽略大写字母)


Search for a string in a string (but ignore capitals)

我想在字符串中搜索一个特殊的字符串,但是脚本应该忽略大写字母。

示例代码:

if (in_string($string, "stringINaSTRING")) {
    echo "The String is in the string!";
}

如果$string包含STRINGINASCTRING,则应返回The String is in the string

我该怎么做呢?

使用不区分大小写的搜索,如stripos()

if (stripos($string, "STRINGINASTRING"))
{
    echo "The String is in the string!";
}

在过去,我通过将字符串变量转换为大写或小写并与大写或小写字符串文字进行比较来完成这一点(在各种不同的语言中)。也就是说:

if (strpos(strtoupper($string), "STRINGINASTRING") !== false) {
    echo "The String is in the string!";
}  

另外,注意使用strpos函数而不是in_string声明。

这个方法只调用字符串转换函数一次,因为你已经知道你应该比较变量的字面值字符串,你可以简单地自己定义它为全大写或全小写(与strtolower一起使用);随你挑。

这个概念背后的一个优点是它适用于没有大小写不敏感函数的语言。对我来说似乎更普遍;但另一方面,用函数来做同样的工作是非常方便的…

if (in_string(strtolower($string), strtolower("stringINaSTRING"))) {
  echo "The String is in the string!";
}