Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ucfirst() function for multibyte character encodings

I've asked about strtolower function. But when using foreign characters it doesn't convert them into uppercase, so I must use:

 mb_strtolower($a,"utf8");

But what can I do, if I want to use ucfirst() function? I haven't found any similar function, where I can set encoding type.

like image 505
Simon Avatar asked Mar 25 '10 17:03

Simon


4 Answers

There is no mb_ucfirst function, as you've already noticed. You can fake a mb_ucfirst with two mb_substr:

function mb_ucfirst($string, $encoding)
{
    $firstChar = mb_substr($string, 0, 1, $encoding);
    $then = mb_substr($string, 1, null, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $then;
}
like image 51
zneak Avatar answered Nov 11 '22 22:11

zneak


This is more concise solution, although it is rather similar to ucwords function:

$final_string = mb_convert_case($your_string, MB_CASE_TITLE, 'UTF-8');

If you need to capitalize string consist of one word, it is the best solution.

like image 32
Alex Belyaev Avatar answered Nov 11 '22 21:11

Alex Belyaev


function mb_ucfirst($string)
{
    return mb_strtoupper(mb_substr($string, 0, 1)).mb_substr($string, 1);
}
like image 30
Koralek M. Avatar answered Nov 11 '22 23:11

Koralek M.


as of 2019-11-18, it seems nobody on stackoverflow got this right, here's how mb_ucfirst() should be implemented in userland:

function mb_ucfirst(string $str, string $encoding = null): string
{
    if ($encoding === null) {
        $encoding = mb_internal_encoding();
    }
    return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr($str, 1, null, $encoding);
}
like image 10
hanshenrik Avatar answered Nov 11 '22 21:11

hanshenrik