【问题标题】:PHP - Capitalise first character of each word expect certain wordsPHP - 大写每个单词的第一个字符,除了某些单词
【发布时间】:2016-03-22 22:42:04
【问题描述】:

我有一批这样的字符串:

tHe iPad hAS gONE ouT of STOCK
PoWER uP YOur iPhone
wHAT moDEL is YOUR aPPLE iPHOne

我想将每个单词的第一个字符大写,其余字符小写——iPhoneiPad 的任何引用除外。如:

通过使用:

ucwords(strtolower($string));

这可以做大部分需要的事情,但显然也可以在iPadiPhone上做:

The Ipad Has Gone Out Of Stock
Power Up Your Iphone
What Model Is Your Apple Iphone

我怎样才能做到以下几点:

The iPad Has Gone Out Of Stock
Power Up Your iPhone
What Model Is Your Apple iPhone

【问题讨论】:

标签: php string lowercase capitalize


【解决方案1】:

您可以为此使用str_replace。如果前两个参数使用数组,则可以定义一组单词和替换:

echo str_replace(['Ipad', 'Iphone'], ['iPad', 'iPhone'], ucwords(strtolower($string)));

来自文档:

如果搜索和替换是数组,则 str_replace() 从每个数组中获取一个值并使用它们来搜索和替换主题。

【讨论】:

    【解决方案2】:

    你知道具体的单词,而且它们是有限的,你为什么不把它们全部大写后恢复回来,就像下面一样

    $string = ucwords(strtolower($string));
    $string = str_replace("Ipad","iPad", $string);
    $string = str_replace ("Iphone","iPhone", $string);
    

    【讨论】:

      【解决方案3】:

      最佳做法是立即在输入字符串上调用strtolower()(syck 的回答没有这样做)。

      我将提供一个纯正则表达式解决方案,该解决方案将适当地定位您的 ipadiphone 单词并将它们的第二个字母大写,同时将所有其他单词的第一个字母大写。

      代码:(PHP Demo) (Pattern Demo)

      $strings = [
          "tHe iPad hAS gONE ouT of STOCK
      PoWER uP YOur iPhone
      wHAT moDEL is YOUR aPPLE iPHOne",           // OP's input string
          "fly the chopper to the helipad.
      an audiphone is a type of hearing aid
      consisting of a diaphragm that, when
      placed against the upper teeth, conveys
      sound vibrations to the inner ear"          // some gotcha strings in this element
      ];
      
      foreach ($strings as $string) {
          echo preg_replace_callback('~\bi\K(?:pad|phone)\b|[a-z]+~', function($m) {return ucfirst($m[0]);}, strtolower($string));
          echo "\n---\n";
      }
      

      输出:

      The iPad Has Gone Out Of Stock
      Power Up Your iPhone
      What Model Is Your Apple iPhone
      ---
      Fly The Chopper To The Helipad.
      An Audiphone Is A Type Of Hearing Aid
      Consisting Of A Diaphragm That, When
      Placed Against The Upper Teeth, Conveys
      Sound Vibrations To The Inner Ear
      ---
      

      关于正则表达式模式可能唯一需要提及的部分是\K 的意思是“重新启动全字符串匹配”,或者换句话说,“使用并忘记当前匹配中的前一个字符”。

      【讨论】:

        【解决方案4】:

        您不必分别编写要排除的每个单词的小写和大写版本,因此必须编写两次,您只需在数组中定义一次并使用 str_ireplace 而不是 str_replace 之类的这个:

        $string = "tHe IPHONE and iPad hAS gONE ouT of STOCK";
        
        $excludedWords = array(
            "iPad",
            "iPhone"
        );
        
        echo str_ireplace($excludedWords, $excludedWords, ucwords(strtolower($string)));
        

        这会导致

        The iPhone And iPad Has Gone Out Of Stock
        

        然后,这会将所有出现的这些单词替换为您在数组中定义的版本。

        编辑:

        请记住,使用这个,“shipadvertise”之类的词将被“shiPadvertise”替换。 如果您想防止这种情况,您可以使用更高级的正则表达式解决方案:

        $string = "tHe IPHONE and shipadvertise iPad hAS gONE ouT of STOCK";
        
        $excludedWords = array(
            "iPad",
            "iPhone"
        );
        $excludedWordsReg = array_map(function($a) { return '/(?<=[\s\t\r\n\f\v])'.preg_quote($a).'/i'; }, $excludedWords);
        
        echo preg_replace($excludedWordsReg, $excludedWords, ucwords(strtolower($string)));
        

        这将正确解析为

        The iPhone And Shipadvertise iPad Has Gone Out Of Stock
        

        我已经使用分隔符来确定 ucwords 默认使用的单词。

        【讨论】:

          【解决方案5】:

          更通用的解决方案:

          <?php
          
          $text = <<<END_TEXT
          PoWER uP YOur iPhone
          tHe iPad hAS gONE ouT of STOCK 
          wHAT moDEL is YOUR aPPLE iPHOne
          END_TEXT;
          
          $text = preg_replace(array('/iphone/i', '/iPad/i'), array('iPhone', 'iPad'), $text);
          $text = preg_replace_callback('/(\b(?!iPad|iPhone)[a-zA-Z0-9]+)/', 
               function ($match) { return ucfirst(strtolower($match[1])); }, $text);
          
          echo $text;
          

          Demo

          在正则表达式中使用否定前瞻来从匹配中排除列出的单词,并通过对匿名函数的回调来操作其他单词。这样,您可以进行任何类型的操作,例如反转字符串。

          【讨论】:

            【解决方案6】:

            这可能会对您有所帮助..我编写此代码供我使用,它对我来说非常适合...

            <?php
            function strtocap($arg){
                $finalStr = array();
            
                $argX = explode(" ",$arg);
                if(is_array($argX)){
                    foreach($argX as $v){
                        $finalStr[] = ucfirst(strtolower($v));
                    }
                }
            return implode(" ",$finalStr);
            }
            
            $str = "Your unForMated StrInG";
            echo strtocap($str);
            ?>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-10-06
              • 2014-04-11
              相关资源
              最近更新 更多