Current Location: Home> Latest Articles> What is the PHP ucwords Function? Detailed Introduction and Basic Usage of ucwords Function

What is the PHP ucwords Function? Detailed Introduction and Basic Usage of ucwords Function

M66 2025-06-16
<?php  
// This article introduces the PHP ucwords function, explaining its purpose and basic usage.  
<p>?></p>
<hr>  
<h2>What is the PHP ucwords Function? Detailed Introduction and Basic Usage of ucwords Function</h2>  
<p>In PHP programming, string manipulation is a common task. Among these tasks, converting the case of strings is one of the most frequently required operations. PHP provides many built-in functions for case conversion, and <strong>ucwords</strong> is one of the most useful functions.</p>  
<h3>1. Definition of the ucwords Function</h3>  
<p>The ucwords function capitalizes the first letter of each word in a string, while leaving the rest of the letters unchanged. Its English meaning is "Upper Case Words," which refers to capitalizing the first letter of each word.</p>  
<pre><code>string ucwords(string $str)

The function accepts a string as an argument and returns the processed string.

2. Basic Usage of the ucwords Function

Here is a simple example demonstrating how to use the ucwords function:

<?php  
$text = "hello world! this is php.";  
echo ucwords($text);  
// Output: Hello World! This Is Php.  
?>

As we can see from the result above, the first letter of each word in the string is capitalized, while the remaining letters are unchanged.

3. Notes on the ucwords Function

  • Definition of words: By default, the ucwords function considers spaces as word separators, so it capitalizes the first letter of each part separated by spaces.
  • Other separators: Since PHP 5.4.32 and PHP 5.5.16, the ucwords function supports a second parameter that allows specifying custom separators. For example:
<?php  
$text = "hello-world_php";  
echo ucwords($text, "-_");  
// Output: Hello-World_Php  
?>

In this example, hyphens and underscores are also treated as word separators, so the letters following them are capitalized.

4. Practical Application Scenarios

  • Beautifying user input text, such as names and titles.
  • Formatting strings to meet title case requirements.
  • Formatting text data stored in databases.

5. Conclusion

The PHP ucwords function is a simple yet practical string manipulation tool that quickly capitalizes the first letter of each word, making it ideal for formatting text. With the additional custom separator feature, ucwords becomes even more versatile, suitable for a variety of use cases.

By understanding and mastering the ucwords function, you can handle string manipulation more efficiently and conveniently.