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
?>
如果输入字符串已经部分大写或全部大写,直接用 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
?>
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>
?>