PHP function: mb_ucfirst


Currently on PHP does not have a multibyte (UTF-8) version of ucfirst function. I wrote some multibyte mb_ucfirst function:

You must call these functions before:

mb_internal_encoding("UTF-8");  // before calling the function
mb_regex_encoding("UTF-8");

Method 1:

if (!function_exists('mb_ucfirst') && function_exists('mb_substr') && function_exists('mb_strtoupper')) {
    function mb_ucfirst($string) {
        $string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
        return $string;
    }
}

Method 2:

if (!function_exists('mb_ucfirst') && function_exists('mb_substr') && function_exists('mb_strtoupper') && function_exists('mb_strtolower') && function_exists('mb_strlen')) {
    function mb_ucfirst($string, $e ='UTF-8') {         
        $string = mb_strtolower($string, $e);
        $upper = mb_strtoupper($string, $e);
        preg_match('#(.)#us', $upper, $matches);
        $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);         
        return $string;
    } 
}

Method 3:

if (!function_exists('mb_ucfirst') && function_exists('mb_strtoupper')) {
    function mb_ucfirst($str){
        preg_match_all("~^(.)(.*)$~u", $str, $arr);
        return mb_strtoupper($arr[1][0]).$arr[2][0];
    } 
}

Method 4:

if (!function_exists('mb_ucfirst') && function_exists('mb_strtolower') && function_exists('mb_strtoupper') && function_exists('mb_substr') && function_exists('mb_strlen'))
{
    function mb_ucfirst($str, $encoding = "UTF-8", $lower_str_end = false)
    {
        $first_letter = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding);
        $str_end = "";
        if ($lower_str_end)
        {
            $str_end = mb_strtolower(mb_substr($str, 1, mb_strlen($str, $encoding), $encoding), $encoding);
        } else
        {
            $str_end = mb_substr($str, 1, mb_strlen($str, $encoding), $encoding);
        }
        $str = $first_letter . $str_end;
        return $str;
    }
}

Method 5: New update 12/02/2015

if (!function_exists('mb_ucfirst') && function_exists('mb_ereg_replace') && function_exists('mb_strtoupper'))
{
    function mb_ucfirst($str)
    {
        return mb_ereg_replace("^(\w)","mb_strtoupper(\"\\1\")",$str,'e');
    }
}

Example:

echo mb_ucfirst("картина");

Result:

Картина

How to make a string’s first character Uppercase-Multibyte?

Leave a Reply