In different situations, you may require making a string completely uppercase or lowercase or camel case letters i.e. capitalize the first letter of each word.
PHP provides built-in functions for that. The functions are listed below which is followed by examples of using them.
- strtoupper() function– For making a PHP string uppercase (all letters in the string)
- strtolower() function – that converts a specified string to lowercase letters.
- ucwords() – camel cased i.e. capitalizes the first letter of each word in a string.
- For making the first letter of a string capital, use the ucfirst() function of PHP.
- In order to make the first letter lowercased, use the lcfirst()
The next section shows you the examples of each function with a little more details.
PHP uppercase conversion by strtoupper function
In the first example, a string variable is created with mixed letter text. The strtoupper function is used and that string variable is specified for converting all letters to capitals. See the code and output:
<?php $str_upper = "Capitalize all letters"; echo strtoupper($str_upper); ?>
Output of the above code is:
CAPITALIZE ALL LETTERS
Convert to small letter example by strtolower function
This example changes the case of all letters to small case letters. The given string is assigned the text with mixed case letters. Have a look at the code and output:
<?php $str_mixed = "SmaLL letters ExamPle"; echo strtolower($str_mixed); ?>
small letters example
Making the first letter of each word capital example
Use the ucwords() function for making the first letter of each word capital in the given string. The following example shows how:
<?php $str_first_cap = "hang on, this is first letter capital example!"; echo ucwords($str_first_cap); ?>
Hang On, This Is First Letter Capital Example!
First letter capital in a string
The ucfirst() function converts only first letter of the specified string to capital. Be noted that, if your string contains multiple sentences then this function still converts only the first letter of the string rather than all sentences.
A demo is shown below where I used multiple sentences:
<?php $str_cap_one = "this is php. php is cool. php is simple."; echo ucfirst($str_cap_one); ?>
This is php. php is cool. php is simple.
Similarly, you may use the lcfirst() function for making the first letter to lowercase.