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)
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>
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>
Top comments (1)
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.