【问题标题】:Capitalize first letter of a string (preceded with special characters) - PHP大写字符串的第一个字母(前面有特殊字符) - PHP
【发布时间】:2012-06-20 14:54:30
【问题描述】:

我想将这样的字符串大写:

¿"hello"?

我希望我的函数返回

¿"Hello"?

我尝试过使用 regex 和 preg_match,但没有成功... 这是我之前的问题,与此相关: "preg_match is matching two characters when it should only match one"

谢谢大家!

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    使用 preg_replace_callback 如上所述 ascii-time,但兼容 unicode:

    echo preg_replace_callback('/^(\PL*)(\pL)/u', function($matches){
        return $matches[1] . mb_strtoupper($matches[2],'UTF-8');
    }, '¿"éllo"?'),"\n";
    

    输出:

    ¿"Éllo"?
    

    【讨论】:

      【解决方案2】:

      您可以使用preg_replace_callback

      preg_replace_callback('/^([^a-z]*)([a-z])/i', function($matches){
          return $matches[1] . strtoupper($matches[2]);
      }, '¿"hello"?');
      
      // ¿"Hello"?
      

      【讨论】:

      • 这接近解决方案,现在我认为我的正则表达式有问题,因为当我的字符串是 '¿ésta prueba?' 时,此函数返回 '¿ésta prueba?'但是“¿Ésta prueba?”预计...
      • 这是发布的最终解决方案:stackoverflow.com/questions/11133485/…
      【解决方案3】:

      试试ucfirst函数http://php.net/manual/en/function.ucfirst.php

      此类任务不需要正则表达式

      样本

      $foo = 'hello world!';
      $foo = ucfirst($foo);             // Hello world!
      

      【讨论】:

        猜你喜欢
        • 2016-03-12
        • 2019-10-19
        • 1970-01-01
        • 1970-01-01
        • 2023-02-23
        • 2017-07-30
        • 1970-01-01
        • 2015-07-24
        • 2020-11-19
        相关资源
        最近更新 更多