ucfirst() function for multibyte character encodin

2020-01-26 07:07发布

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.

8条回答
时光不老,我们不散
2楼-- · 2020-01-26 07:48
if (!function_exists('mb_ucfirst'))
{
    function mb_ucfirst($value)
    {
        return mb_strtoupper(mb_substr($value, 0, 1)) . mb_substr($value, 1);
    }
}
查看更多
老娘就宠你
3楼-- · 2020-01-26 07:48

I´m using cp1250 on webpage, and for Ú mb_ucfirst doesn´t work, so little upgrade:

  function mb_ucfirst($string)
{
    $main_encoding = "cp1250"; 
    $inner_encoding = "utf-8";
    $string = iconv($main_encoding, $inner_encoding , $string );
    $strlen = mb_strlen($string);
    $firstChar = mb_substr($string, 0, 1, $inner_encoding);
    $then = mb_substr($string, 1, $strlen - 1, $inner_encoding);
    return $string = iconv($inner_encoding, $main_encoding , mb_strtoupper($firstChar, $inner_encoding) . $then );
}
查看更多
叛逆
4楼-- · 2020-01-26 07:55
$string = trim(preg_replace('/\s+/', ' ', $string));
$string_ar = explode(' ', mb_strtolower($string,'utf-8'));

foreach($string_ar as $key => $value {
  $string_str .= mb_convert_case(mb_substr(trim($value), 0, 1), MB_CASE_TITLE, 'utf-8')
    . mb_substr(trim($value),1)
    . ' ';
}

$string = trim($string_str);
查看更多
趁早两清
5楼-- · 2020-01-26 07:58
function mb_ucfirst($string)
{
    return mb_strtoupper(mb_substr($string, 0, 1)).mb_strtolower(mb_substr($string, 1));
}
查看更多
混吃等死
6楼-- · 2020-01-26 08:06

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)
{
    $strlen = mb_strlen($string, $encoding);
    $firstChar = mb_substr($string, 0, 1, $encoding);
    $then = mb_substr($string, 1, $strlen - 1, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $then;
}
查看更多
成全新的幸福
7楼-- · 2020-01-26 08:10
/*This worked correctly for me*/
function mb_ucfirst($string, $encoding='UTF-8')
{
    $firstChar = mb_substr($string, 0, 1, $encoding);
    $then = mb_substr($string, 1, mb_strlen($string, $encoding)-1, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $then;
}
查看更多
登录 后发表回答