當前位置: 首頁> 最新文章列表> 使用ucwords 實現標題格式化時常見的錯誤有哪些?如何避免?

使用ucwords 實現標題格式化時常見的錯誤有哪些?如何避免?

gitbox 2025-06-08

2. 忽略單詞間分隔符的多樣性

ucwords默認只會把以空格分隔的單詞首字母大寫,但如果字符串中有其他分隔符,比如連字符(-)、下劃線(_)等, ucwords不會識別。

 <?php
$title = "my-php_script example";
$formatted = ucwords($title);
echo $formatted;  // 輸出:My-php_script Example
?>

此時,“php_script” 依然是小寫,未正確格式化。

避免方法:可以自定義分隔符,或者先替換其他分隔符為空格,處理完後再恢復。

 <?php
function ucwords_custom($string, $delimiters = ['-', '_']) {
    foreach ($delimiters as $delimiter) {
        $string = str_replace($delimiter, ' ', $string);
    }
    $string = ucwords($string);
    foreach ($delimiters as $delimiter) {
        $string = str_replace(' ', $delimiter, $string);
    }
    return $string;
}

echo ucwords_custom("my-php_script example");  // 輸出:My-PHP_Script Example
?>

3. 不考慮大小寫敏感性導致格式不統一

如果輸入字符串已經部分大寫或全部大寫,直接用ucwords可能導致結果混亂。

 <?php
$title = "tHe quick bROWN foX";
$formatted = ucwords($title);
echo $formatted;  // 輸出:THe Quick BROWN FoX
?>

此時部分單詞依舊是大小寫混合,沒達到標題格式的效果。

避免方法:先統一字符串為全小寫,再使用ucwords

 <?php
$title = "tHe quick bROWN foX";
$formatted = ucwords(strtolower($title));
echo $formatted;  // 輸出:The Quick Brown Fox
?>

4. 處理帶有HTML標籤或URL的字符串時出現錯誤

ucwords處理純文本效果好,但如果字符串中含有HTML標籤或URL,直接調用會破壞標籤和鏈接。

 <?php
$title = 'visit <a href="https://gitbox.net/path">our site</a>';
echo ucwords($title);
// 結果會錯誤處理標籤,變成 Visit <A Href="Https://Gitbox.Net/Path">Our Site</A>
?>

避免方法:可以先提取標籤,處理文本部分,再拼接回去,或者針對URL做保護。一個簡單做法是跳過HTML標籤。

 <?php
function ucwords_without_tags($text) {
    return preg_replace_callback('/([^<>]+)(?=<|$)/', function($matches) {
        return ucwords(strtolower($matches[1]));
    }, $text);
}

echo ucwords_without_tags('visit <a href="https://gitbox.net/path">our site</a>');
// 輸出:Visit <a href="https://gitbox.net/path">Our Site</a>
?>