【问题标题】:PHP switch/case statement with case-insensitive string comparison具有不区分大小写的字符串比较的 PHP switch/case 语句
【发布时间】:2015-03-31 23:43:27
【问题描述】:

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

<?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”。我该怎么做?

【问题讨论】:

  • 你有什么问题?
  • 为什么你认为 switch 语句不区分大小写? crikeyCrikey 不一样。知道这一点,解决它和strtoupperstrtolower 的值。或者,在进行比较时将变量的第一个字母大写。另外,你为什么要这样呢?
  • 他刚刚告诉你——用 strtolower($smart) 强制所有内容为小写,让你的大小写为“crickey”:等等。
  • 只需使用小写字符串来切换和更新您的案例:eval.in/307176

标签: php


【解决方案1】:

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

<?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";
}
?>

【讨论】:

    【解决方案2】:

    在 case 语句中使用 stristr() 函数。 stristr() 不区分大小写 strstr() 并且返回从第一次出现的 needle 到结束的所有 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";
    }
    
    ?>
    

    【讨论】:

      【解决方案3】:

      如果您使用小写输入,那么您可以将它们转换为字符串中每个单词的首字母大写

      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";
      }
      ?>
      

      来自文档的有用链接:

      first character of each word
      Make a string's first character uppercase
      Make a string lowercase
      Make a string uppercase

      【讨论】:

        猜你喜欢
        • 2013-10-11
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多