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.
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.
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.
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.
<?php
$str = "welcome to the m66.net-php tutorial, let's learn ucwords!";
echo ucwords($str, " -'");
?>
Output: