Current Location: Home> Latest Articles> What Are the Common Mistakes When Using ucwords for Title Formatting? How to Avoid Them?

What Are the Common Mistakes When Using ucwords for Title Formatting? How to Avoid Them?

gitbox 2025-06-08

2. Ignoring the Diversity of Word Separators

ucwords by default only capitalizes the first letter of words separated by spaces. However, if there are other delimiters in the string, such as hyphens (-) or underscores (_), ucwords will not recognize them.

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

In this case, "php_script" remains in lowercase and is not correctly formatted.

Solution: You can customize the delimiters or replace other separators with spaces first, process them, and then restore the original separators.

<?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;
}
<p>echo ucwords_custom("my-php_script example");  // Output: My-PHP_Script Example<br>
?><br>


3. Inconsistent Formatting Due to Case Sensitivity

If the input string already has some uppercase or is entirely in uppercase, directly using ucwords might result in a jumbled output.

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

In this case, some words remain in mixed case, not achieving the intended title case formatting.

Solution: First, convert the string to all lowercase, and then use ucwords.

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

4. Errors When Handling Strings Containing HTML Tags or URLs

ucwords works well for plain text, but if the string contains HTML tags or URLs, directly calling it will break the tags and links.

<?php
$title = 'visit <a href="https://gitbox.net/path">our site</a>';
echo ucwords($title);
// The result will incorrectly process the tags and output: Visit <A Href="Https://Gitbox.Net/Path">Our Site</A>
?>

Solution: You can first extract the tags, process the text part, and then reassemble the string, or protect URLs. A simple approach is to skip over HTML tags.

<?php
function ucwords_without_tags($text) {
    return preg_replace_callback('/([^<>]+)(?=<|$)/', function($matches) {
        return ucwords(strtolower($matches[1]));
    }, $text);
}
<p data-is-last-node="" data-is-only-node="">echo ucwords_without_tags('visit <a href="<a rel="noopener" target="_new" class="cursor-pointer">https://gitbox.net/path">our</a> site</a>');<br>
// Output: Visit <a href="<a rel="noopener" target="_new" class="cursor-pointer">https://gitbox.net/path">Our</a> Site</a><br>
?><br>