ucwords() Function Use in PHP 8.4 and PHP 8.5

The ucwords() function works the same way in PHP 8.4 and PHP 8.5. There are no version specific changes for this function in either release. The most recent significant update was in PHP 8.2.0, which made its case conversion strictly ASCII based, independent of the server is locale settings.

Function

ucwords() returns a string with the first character of each word converted to uppercase, if that character is an ASCII letter between "a"and “z”.

Signature:

ucwords(string $string, string $separators = " fv"): string

Key Behavior:

  • Word Definition: A "word" is any sequence of characters immediately following one of the defined separators. By default, these are space, horizontal tab, carriage return, newline, form-feed, and vertical tab.
  • Custom Separators: You can pass a second argument to specify additional characters that should act as word boundaries (e.g., | or ).
  • Multibyte Strings: This function only handles ASCII characters. For UTF-8 or other multibyte encodings, you should use mb_convert_case() with the MB_CASE_TITLE mode instead.

Example

A common use case is formatting a user is name or a title:

<?php
$title = hello world! ;
echo ucwords($title);
// Outputs: Hello World!

// Example with a custom separator (hyphen)
$name = jean-luc picard ;
echo ucwords($name, " -");
// Outputs: Jean-Luc Picard
?>

Important Note

If the input string is already in all uppercase (e.g., HELLO WORLD ), ucwords() will not lowercase the remaining letters. It will simply return the string unchanged because the first character is already uppercase. To normalize a string to "Title Case," you typically need to lowercase it first:

<?php 

$bar = HELLO WORLD! ;

echo ucwords(strtolower($bar)); 

// Outputs: Hello World!

?>


 

20 Views