在PHP中==是否区分大小写的字符串比较?


Answers:



20

是的,但是它逐字节进行比较。

如果要比较unicode字符串,则可能希望先对其进行规范化。见Normalizer上课。

示例(UTF-8中的输出):

$s1 = mb_convert_encoding("\x00\xe9", "UTF-8", "UTF-16BE");
$s2 = mb_convert_encoding("\x00\x65\x03\x01", "UTF-8", "UTF-16BE");
//look the same:
echo $s1, "\n";
echo $s2, "\n";
var_dump($s1 == $s2); //false
var_dump(Normalizer::normalize($s1) == Normalizer::normalize($s2)); //true

3
+1表示不是真正的字符串比较(二进制比较)。因此,它在技术上不区分大小写(尽管在99.999%的情况下,它的行为就像它一样)...
ircmaxell 2010年

11

是的,==区分大小写。

顺便提及,对于不区分大小写的比较,请使用strcasecmp

<?php
    $var1 = "Hello";
    $var2 = "hello";
    echo (strcasecmp($var1, $var2) == 0); // TRUE;
?>



1

是的,==区分大小写。对我而言,最简单的方法是转换为大写字母然后进行比较。例如:

$var = "Hello";
if(strtoupper($var) == "HELLO") {
    echo "identical";
}
else {
    echo "non identical";
}

我希望它能起作用!


0

您可以尝试与哈希函数进行比较

  if( md5('string1') == md5('string2') ) {
    // strings are equal
  }else {
    // strings are not equal
  }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.