Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在字符串中搜索字符串(但忽略大写)_Php - Fatal编程技术网

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

Php 在字符串中搜索字符串(但忽略大写),php,Php,我想在字符串中使用特殊字符串,但是脚本应该忽略大写字母 示例代码: if (in_string($string, "stringINaSTRING")) { echo "The String is in the string!"; } 如果$string包含stringinascorting它应该回显字符串在字符串中 如何完成此操作?将所有内容转换为较低的 if (in_string(strtolower($string), strtolower("stringINaSTRING"))

我想在字符串中使用特殊字符串,但是脚本应该忽略大写字母

示例代码:

if (in_string($string, "stringINaSTRING")) {
    echo "The String is in the string!";
}
如果
$string
包含
stringinascorting
它应该回显
字符串在字符串中


如何完成此操作?

将所有内容转换为较低的

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

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


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

if (strpos(strtoupper($string), "STRINGINASTRING") !== false) {
    echo "The String is in the string!";
}  
另外,请注意使用了
strpos
函数,而不是字符串中的
声明

这种方法只调用字符串转换函数一次,因为您已经知道应该将变量与之进行比较的文本字符串,您可以自己将其定义为全大写或全小写(与strtolower一起使用);你挑吧


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

或者将每个字符串转换为小写,然后进行比较。如果您从页面中获得
in_string
函数,则有一个区分大小写的选项<代码>字符串中的函数($needle,$haystack,$insensitive=false)
如果
字符串中的
是一个实际的函数,那么它可能是一个不错的答案。strpos()会更快。@develonnate我怀疑
strpos()
会更快,因为你必须在搜索字符串上调用
strtolower()
。但是
stripos()
肯定更快。啊,好吧,你说得对。稍微快一点,但更快一点:@develenimate哇,比我预想的要近得多。我又跑了几次,它来回跑,其中一个跑得更快。我打赌
stripos()
正在做一些类似于
strpos()/strtolower()
的事情,如果搜索字符串位于干草堆的开头怎么办?strpos将返回0,这将导致比较失败。如果(strpos($haystack,$needle)!==false)是一个更好的方法。@develinnate同意,更新答案。类似地,
=0
也可以代替
!=false
@DEVLINATIONE这就是为什么您应该使用
===
而不是
=
如果找不到字符串,它将返回false和
0!==false
为false,但
0!=false
为空true@Robert:答案原来是if(strpos($haystack,$needle){//find},这就是我的评论的目的。这个答案后来被更新/编辑了。好的,我不知道
if (strpos(strtoupper($string), "STRINGINASTRING") !== false) {
    echo "The String is in the string!";
}