Make first letter uppercase and the rest lowercase in a string

后端 未结 10 1972
醉梦人生
醉梦人生 2020-12-13 12:25

All, I\'m trying to insert a last name into a database. I\'d like the first letter to be capitalized for the name and if they have use two last names then capitalize the fir

10条回答
  •  星月不相逢
    2020-12-13 13:10

    This is a little more simple and more direct answer to the main question. the function below mimics the PHP approachs. Just in case if PHP extend this with their namespaces in the future, a test is first checked. Im using this water proof for any languages in my wordpress installs.

    $str = mb_ucfirst($str, 'UTF-8', true);
    

    This make first letter uppercase and all other lowercase as the Q was. If the third arg is set to false (default), the rest of the string is not manipulated.

    // Extends PHP
    if (!function_exists('mb_ucfirst')) {
    
    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;
    }
    
    }
    

    / Lundman

提交回复
热议问题