DEV Community

Lalit Kumar
Lalit Kumar

Posted on

PHP capitalize first letter of each word

In this topic, we will learn and explore how can we capitalize on the first letter of each word in PHP .PHP has a variety of inbuilt functions to make things easy and in a quick manner. PHP has a variety of inbuilt functions to deal with strings which help us to perform our desired task efficiently. Letโ€™s discuss one of the best and a very helping method of PHP to capitalize on each first character of each word of a given string.

Capitalizing the first letter of each word by using the ucwords() function.

PHP introduced the ucwords () function in its 4th version to process strings, and to assist the programmers in capitalizing the first letter of each word. Here we are going to discuss its syntax and how it works. We will check this method with examples.


title: "originally posted here ๐Ÿ‘‡"

canonical_url: https://kodlogs.com/blog/2599/php-capitalize-first-letter-of-each-word

Ucwords() function

This function is used to convert/ capitalize the first character of each word in strings. It is supported by all versions of PHP starting from the 4th version.

Syntax

ucwords(string, delimiters)
Enter fullscreen mode Exit fullscreen mode

Ucwords function contains tow parameters, first parameter is โ€œstringโ€ that is required and must be provided to get desired results. While the other one is an option and it is called delimiter, it will not affect the execution if you skip this parameter.

Ucwords () on strings and arrays

Here we will try this method on a string with a single parameter and with double parameters using a delimiter.

Example:

<html>
<body>

<?php
echo ucwords("hello mr coder, enjoy coding php.");
echo '</br>';

 //using delimiter 

 echo ucwords("hello| coder", '|');

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How does the ucwords () function work on arrays?

This example will illustrate how can we use ucwords on arrays to capitalize on the first character of each word of string arrays.

<?php
$names =array(
  'john peter',
  'musa ahmad',
  'William parker',
  'yasir abbas',
  'brain larra'
);
foreach ($names as $name) {
print ucwords("{$name}\n").'</br>'; }

//PRINTS:
John Peter
Musa Ahmad
William Parker
Yasir Abbas
Brain Larra 
?>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Read more in original post

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair

If you're using PHP to generate HTML documents, I'd massively recommend using CSS for this instead. There's no reason for search engines, etc., to know your text as title-case when it doesn't need to be, and if you want to display it differently elsewhere or decide later on to change it you need to rebuild your code rather than tweak a stylesheet.