Current Location: Home> Latest Articles> How to Use the ucwords Function to Modify Long Strings Containing Spaces and Punctuation for Ideal Capitalization?

How to Use the ucwords Function to Modify Long Strings Containing Spaces and Punctuation for Ideal Capitalization?

gitbox 2025-06-19

In PHP, the ucwords function is a commonly used method to capitalize the first letter of each word in a string. Its default behavior is to split words by spaces, but when the string contains punctuation or other non-alphabetic characters, ucwords might not achieve the desired capitalization effect. This article will explain how to use ucwords combined with other techniques to handle long strings containing spaces and punctuation, achieving more accurate capitalization conversion.

1. Basic Usage of ucwords

ucwords only capitalizes the first letter of words separated by spaces. For example:

<?php
$str = "hello world! this is php.";
echo ucwords($str);
?>

Output:

Hello World! This Is Php.

As you can see, letters following punctuation are correctly handled, but if the string contains other punctuation such as hyphens or apostrophes, ucwords will not automatically process them.

2. The Second Parameter of ucwords - Defining Word Separators (PHP 5.4+)

Starting from PHP 5.4, the ucwords function supports a second parameter, which allows you to define characters as word separators. For example:

<?php
$str = "jack-o'-lantern's day";
echo ucwords($str, " -'");
?>

Output:

Jack-O'-Lantern'S Day

Here, we specified spaces, hyphens -, and apostrophes ' as separators, so the first letter after each separator is also capitalized.

3. Using Regular Expressions for More Flexible Capitalization

If the string structure is complex, relying solely on ucwords is not flexible enough. You can combine it with regular expressions to capitalize the first letter of each word:

<?php
$str = "this is a complex-string, isn't it? yes!";

$callback = function ($matches) {
    return strtoupper($matches[1]) . strtolower(substr($matches[0], 1));
};

$result = preg_replace_callback('/\b\w/u', $callback, $str);

echo $result;
?>

Output:

This Is A Complex-String, Isn't It? Yes!

This code uses preg_replace_callback to find the first letter of each word and convert it to uppercase, while ensuring the remaining letters are lowercase.

4. Complete Example: Combining ucwords with Custom Separators

<?php
$str = "welcome to the m66.net-php tutorial, let's learn ucwords!";

echo ucwords($str, " -'");

?>

Output: