In different situations, you may require making a string completely uppercase or lowercase or camelcase letters i.e. capitalize the first letter of each word.
PHP provides built-in functions for that. The functions are given below which are followed by examples of using them.
Function | Description |
strtoupper() | strtoupper() function– For making a PHP string uppercase (all letters in the string) |
strtolower() | strtolower() function – that converts a specified string to lowercase letters. |
ucwords() | ucwords() – camel cased i.e. capitalizes the first letter of each word in a string. |
ucfirst() | For making the first letter of a string capital, use the ucfirst() function of PHP. |
lcfirst() | 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:
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); ?>
Output:
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:
Oode:
<?php $str_first_cap = "hang on, this is first letter capital example!"; echo ucwords($str_first_cap); ?>
The output:
First letter capital in a string
The ucfirst() function converts only the first letter of the specified string to capital.
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); ?>
The output: