PHP 句首大写函数实现


PHP 封装字符串、句首大写函数调用

    /**
     * 句首大写
     * 参考 https://www.php.net/manual/zh/function.ucfirst.php
     * @param $str
     * @return string 句子首字母大写的返回字符串 return string with first letters of sentences capitalized
     */
   function ucfirst_format($str)
    {
        if ($str) { // input
            $str = preg_replace('/' . chr(32) . chr(32) . '+/', chr(32), $str); // recursively replaces all double spaces with a space
            if (($x = substr($str, 0, 10)) && ($x == strtoupper($x))) $str = strtolower($str); // sample of first 10 chars is ALLCAPS so convert $str to lowercase; if always done then any proper capitals would be lost
            $na = array('. ', '! ', '? '); // punctuation needles
            foreach ($na as $n) { // each punctuation needle
                if (strpos($str, $n) !== false) { // punctuation needle found
                    $sa = explode($n, $str); // split
                    foreach ($sa as $s) $ca[] = ucfirst($s); // capitalize
                    $str = implode($n, $ca); // replace $str with rebuilt version
                    unset($ca); //  clear for next loop
                }
            }
            return ucfirst(trim($str)); // capitalize first letter in case no punctuation needles found
        }
    }


云天阁
非我而当者,吾师也;是我而当者,吾友也;谄谀我者,吾贼也。
搜索