PHP has four everyday functions for changing the case of text.
| Function | What it does | Example result |
|---|---|---|
strtoupper() | ALL CAPITALS | HELLO WORLD |
strtolower() | all small letters | hello world |
ucfirst() | Capital first letter | Hello world |
ucwords() | Capital first letter of each word | Hello World |
<?php
$text = "hello wORLD";
echo strtoupper($text) . "\n";
echo strtolower($text) . "\n";
echo ucfirst($text) . "\n";
echo ucwords($text);
HELLO WORLD
hello world
Hello wORLD
Hello WORLD
ucfirst() and ucwords() do not lower the other letters. To normalise text, lower it first.
<?php
$name = "aNiL kUMAR";
echo ucwords(strtolower($name));
Anil Kumar
Compare text without caring about case
Lower both sides before comparing.
<?php
$typed = "YES";
if (strtolower($typed) === "yes") {
echo "Confirmed";
}
Confirmed
Lowercase an email
Email addresses are usually compared in lowercase.
<?php
$email = " Ravi@Example.COM ";
echo strtolower(trim($email));
ravi@example.com
Names have exceptions
ucwords() is great for simple cases, but names like “McDonald” or “van der Berg” will be changed incorrectly. Do not force the case of real names. Accept what the user typed.
Text with accents
The plain functions work on English letters. For other alphabets, use the mb_ versions.
<?php
echo mb_strtoupper("zoë café");
ZOË CAFÉ
In PHP 8.4 there are also mb_ucfirst() and mb_lcfirst().
Slugs are lowercase
/blog/My-Post and /blog/my-post can be seen as different pages. Make slugs lowercase with strtolower().