Using of regex with preg_replace_callback

后端 未结 1 1514
夕颜
夕颜 2021-01-24 07:30

I\'d like to capitalize the first letter of a string which could have special characters (that\'s the reason ucfirst is not valid here). I have next code:

$string         


        
相关标签:
1条回答
  • 2021-01-24 08:06

    This is because your a-z will not match é. Writing a regex to encompass unicode characters may be difficult.

    From your code it will only capitalise the first letter, regardless of the amount of words in your string. If so just do this:

    $string = 'ésta';
    $ucstring = ucphrase($string);
    
    function ucphrase($word) {
      return mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
    }
    

    The mb_* functions should handle your special characters correctly.


    Based on your comment below I understand your dilemma. In that case you can use your regular expression but with the correct unicode selectors

    $string = 'ésta';
    $pattern = '/(\p{L})(.+)/iu';
    
    $callback_fn = 'process';
    
    echo preg_replace_callback($pattern, $callback_fn, $string);
    
    
    function process($matches){
        return mb_strtoupper($matches[1], 'UTF-8') . $matches[2];
    }
    
    0 讨论(0)
提交回复
热议问题