In PHP, the ucwords function is commonly used 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-letter characters, ucwords may not produce the ideal case conversion. This article will explain how to combine ucwords with other techniques to process long strings with spaces and punctuation, achieving more accurate case transformations.
ucwords will only capitalize 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, the letters after punctuation are handled correctly. However, if the string contains other punctuation marks, such as hyphens or apostrophes, ucwords will not automatically handle them.
Starting from PHP 5.4, the ucwords function supports a second parameter to define which characters are treated as word delimiters. For example:
<?php
$str = "jack-o'-lantern's day";
echo ucwords($str, " -'");
?>
Output:
Jack-O'-Lantern'S Day
Here, spaces, hyphens -, and apostrophes ' are specified as delimiters, causing the first letter after each delimiter to be capitalized as well.
If the string structure is more complex, relying solely on ucwords might not be flexible enough. In such cases, you can combine regular expressions to capitalize the first letter of each word:
<?php
$str = "this is a complex-string, isn't it? yes!";
<p>$callback = function ($matches) {<br>
return strtoupper($matches[1]) . strtolower(substr($matches[0], 1));<br>
};</p>
<p>$result = preg_replace_callback('/\b\w/u', $callback, $str);</p>
<p>echo $result;<br>
?><br>
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!";
<p>echo ucwords($str, " -'");</p>
<p>?><br>
Output: