【问题标题】:Convert the first letter to Capital letter but ONLY for UPPERCASE strings - PHP将第一个字母转换为大写字母,但仅适用于大写字符串 - PHP
【发布时间】:2012-09-28 13:16:59
【问题描述】:

谁能帮我做这件事?

例如我有一串

SOME of the STRINGS are in CAPITAL Letters

我真正想要的输出是

Some of the Strings are in Capital Letters

只有大写字母的首字母大写,其余字母小写。

如何使用 PHP 实现这一点?

提前致谢。

【问题讨论】:

  • 哦,cmon,你可以对正则表达式和字符串函数做一些研究,然后试一试。
  • 是的,好吧。 stackoverflow 有什么用? -_-还是谢谢
  • 它是为了在您已经尝试自己解决的问题上获得帮助。你所拥有的根本没有尝试解决问题。
  • 抱歉,我试过了,但我不能,所以我寻求帮助。不要做一个好人,它不适合你:D。请研究一下“”按钮的作用。无论如何,谢谢,它已经解决了。感谢其他人。

标签: php


【解决方案1】:

您可以使用preg_replace_callback 查找所有大写单词并将其替换为自定义回调函数

【讨论】:

    【解决方案2】:

    快速示例:

    $input = "SOME of the STRINGS are in CAPITAL Letters";
    $words = explode(" ",$input);
    $output = array();
    foreach($words as $word)
    {
        if (ctype_upper($word)) $output[] = $word[0].strtolower(substr($word,1));
        else $output[] = $word;
    }
    $output = implode($output," ");
    

    输出:

    有些字符串是大写的

    【讨论】:

      【解决方案3】:

      您可以使用strtolowerucwords

      $word = "SOME of the STRINGS are in CAPITAL Letters";
      echo ucwords(strtolower($word));
      

      输出

      Some Of The Strings Are In Capital Letters
      

      如果你想要它完全按照你描述的方式

      $word = "SOME of the STRINGS are in CAPITAL Letters";
      $word = explode(" ", $word);
      $word = array_map(function ($word) {return (ctype_upper($word)) ?  ucwords(strtolower($word)) : $word;}, $word);
      echo implode(" ", $word);
      

      输出

       Some of the Strings are in Capital Letters
      

      【讨论】:

      • 抱歉,输出是“Some The Strings Are In Capital Letters”
      • "只有大写字母的首字母大写,其余字母小写。"
      • 第二个看起来不错。但是您需要先映射小写字母。总之谢谢
      • 谢谢 .. 添加改进版本以输出“某些字符串为大写字母”
      • 注意:这个函数会去掉已有的大写,例如单词“Letters”变成了“letters”。
      【解决方案4】:

      如果你想避免正则表达式

      $text = "SOME of the STRINGS are in CAPITAL Letters";
      
      $str_parts = explode(" ", $text);
      
      foreach ($str_parts as $key => $str_part)
      {
        if (ctype_upper($str_part) == strtolower(substr($str_part,1)))
        {
          $str_parts[$key] = ucfirst(strtolower($str_part));;
        }
      }
      
      $text = implode($str_parts, " ");
      
      echo $text;
      

      【讨论】:

        【解决方案5】:

        感谢您的回答,真的很有帮助,它给了我一些想法。 我也使用 preg_replace,只是分享给可能需要的人。

        preg_replace('/([A-Z])([A-Z ]+)/se', '"\\1" . strtolower("\\2")', $str);
        

        preg_replace('/([?!]{2})([?!]+)/', '\1', $str);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-04
          • 1970-01-01
          • 1970-01-01
          • 2015-07-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多