PHP switch/case语句,具有不区分大小写的字符串比较


PHP switch/case statement with case-insensitive string comparison

开关/大小写字符串比较区分大小写。

<?php
$smart = "crikey";
switch ($smart) {
     case "Crikey":
         echo "Crikey";
         break;
     case "Hund":
         echo "Hund";
         break;
     case "Kat":
         echo "Kat";
         break;
     default:
         echo "Alt Andet";
}
?>

上面的代码打印"Alt Andet",但我想不区分大小写地比较字符串并打印"Crikey"。我该怎么做?

将输入转换为大写或小写,问题已解决。

<?php
$smart = "cRikEy";
switch (strtolower($smart)) {
     case "crikey": // Note the lowercase chars
         echo "Crikey";
         break;
     case "hund":
         echo "Hund";
         break;
     case "kat":
         echo "Kat";
         break;
     default:
         echo "Alt Andet";
}
?>

对case语句使用stristr()函数。stristr()不区分大小写的strstr(),并且返回从针的第一次出现开始到结束的所有haystack

<?php
$smart = "crikey";
switch ($smart) {
     case stristr($smart, "Crikey"):
         echo "Crikey";
         break;
     case stristr($smart, "Hund"):
         echo "Hund";
         break;
     case stristr($smart, "Kat"):
         echo "Kat";
         break;
     default:
         echo "Alt Andet";
}
?>

如果使用小写输入,则可以将它们转换为字符串中每个单词的大写第一个字符

ucwords—将字符串中每个单词的第一个字符大写

<?php
$smart = "crikey";
switch (ucwords($smart)) {
     case "Crikey":
         echo "Crikey";
         break;
     case "Hund":
         echo "Hund";
         break;
     case "Kat":
         echo "Kat";
         break;
     default:
         echo "Alt Andet";
}
?>

文档中的有用链接:

每个单词的第一个字符
使字符串的第一个字符大写
使字符串小写
使字符串大写