One of the nice things about working with strings in PHP is its huge range of built-in string-handling functions. If you want to do something to a string, chances are there’s a PHP function to do it for you!
In this article you’ll look at PHP’s string functions for converting text between uppercase and lowercase:
strtolower()
for converting a string to lowercasestrtoupper()
for converting a string to uppercaselcfirst()
for converting the first letter to lowercaseucfirst()
for converting the first letter to uppercaseucwords()
for converting each word to uppercase
Converting a whole string to lowercase with strtolower()
strtolower()
takes a string of text, and returns a copy of the string with all letters converted to lowercase:
$myString = 'Hello there! How are you?';
echo strtolower( $myString ); // Displays "hello there! how are you?"
strtolower()
is handy if you want to ensure that automatically-generated URLs, filenames, or passwords are all in lowercase. It’s also useful for comparing 2 strings regardless of their case (for example, “Hello” and “hello”) &mdash just convert both strings using strtolower()
before comparing them:
$myString1 = 'Hello!';
$myString2 = 'hello!';
// Displays "Strings match"
if ( strtolower( $myString1 ) == strtolower( $myString2 ) ) echo "Strings match";
Converting a whole string to uppercase with strtoupper()
strtoupper()
does the opposite of strtolower()
, converting an entire string to uppercase letters:
$myString = 'Hello there! How are you?';
echo strtoupper( $myString ); // Displays "HELLO THERE! HOW ARE YOU?"
Converting the first letter to lowercase with lcfirst()
lcfirst()
converts just the first letter of a string to lowercase:
$myString = 'Hello there! How are you?';
echo lcfirst( $myString ); // Displays "hello there! How are you?"
Converting the first letter to uppercase with ucfirst()
ucfirst()
— the counterpart to lcfirst()
— converts just the first letter of a string to uppercase:
$myString = 'hello there! how are you?';
echo ucfirst( $myString ); // Displays "Hello there! how are you?"
Converting the first letter of each word to uppercase with ucwords()
The ucwords()
function converts the first letter of each word in a string to uppercase — great for formatting page titles and so on:
$myString = 'Hello there! How are you?';
echo ucwords( $myString ); // Displays "Hello There! How Are You?"
As far as ucwords()
is concerned, a “word” is any string of letters that follows whitespace (or that is at the start of the string).
You now know how to convert case in PHP. You’ve looked at strtolower()
and strtoupper()
for converting whole strings; lcfirst()
and ucfirst()
for converting just the first letter of a string; and ucwords()
for converting the first letter of each word to uppercase.
Happy coding! If you have any questions on converting the case of PHP strings, feel free to post a response below.
Leave a Reply