在 PHP 中比较字符串时忽略大小写敏感
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1650864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ignore case sensitivity when comparing strings in PHP
提问by Donal.Lynch.Msc
I'm trying to compare words for equality, and the case [upper and lower] is irrelevant. However PHP does not seem to agree! Any ideas as to how to force PHP to ignore the case of words while comparing them?
我正在尝试比较单词是否相等,大小写 [upper and lower] 无关紧要。然而PHP似乎并不同意!关于如何强制 PHP 在比较单词时忽略单词大小写的任何想法?
$arr_query_words = array( "hat","Cat","sAt","maT" );
// for each element in $arr_query_words -
for( $j= 0; $j < count( $arr_query_words ); $j++ ){
// Split the $query_string on "_" or "%" :
$story_body = str_replace( $arr_query_words[ $j ],
'<span style=" background-color:yellow; ">' . $arr_query_words[ $j ] . '</span>',
$story_body );
// --- This ONLY replaces where the case [upper or lower] is identical ->
}
Is there a way to carry out the replace even if the case is different?
即使情况不同,有没有办法进行更换?
回答by Dominic Rodger
Use str_ireplaceto perform a case-insensitive string replacement (str_ireplaceis available from PHP 5):
使用str_ireplace以执行不区分大小写的字符串替换(str_ireplace可从PHP 5):
$story_body = str_ireplace($arr_query_words[$j],
'<span style=" background-color:yellow; ">'. $arr_query_words[$j]. '</span>',
$story_body);
To case-insensitively compare strings, use strcasecmp:
要不区分大小写比较字符串,请使用strcasecmp:
<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>
回答by Tim Visée
The easiest, and most widely supported way to achieve this is possibly to lowercase both strings before comparing them, like so:
实现此目的的最简单且最受广泛支持的方法可能是在比较之前将两个字符串小写,如下所示:
if(strtolower($var1) == strtolower($var2)) {
// Equals, case ignored
}
You might want to trim the strings being compared, simply use something like this to achieve this functionality:
您可能想要修剪正在比较的字符串,只需使用以下内容即可实现此功能:
if(strtolower(trim($var1)) == strtolower(trim($var2))) {
// Equals, case ignored and values trimmed
}
回答by Mitja
回答by Thusitha Sumanadasa
$var1 = "THIS is A teST";
$var2 = "this is a tesT";
if (strtolower($var1) === strtolower($var2) ) {
echo "var1 and var2 are same";
}
strtolowerconverts string to lowercase
strtolower将字符串转换为小写
回答by Luca C.
if(!strcasecmp($str1, $str2)) ... //they are equals ignoring case
strcasecmp returns 0 only if strings are equals ignoring case, so !strcasecmp return true if they are equals ignoring case, false otherwise
strcasecmp 仅在字符串等于忽略大小写时返回 0,所以 !strcasecmp 如果它们等于忽略大小写,则返回 true,否则返回 false
回答by coder
I always just add the ascii difference between upper and lower case to the the lower case chars.
我总是将大写和小写之间的 ascii 差异添加到小写字符中。

