Text transformation in PHP

In this tutorial we'll look at 5 functions which can be used to transform the capitalization of strings in PHP. This is good for preparing and formatting strings for output to the users.

Converting strings to upper and lower case

The functions strtolower and strtoupper convert strings to all lowercase and all uppercase respectively:

<?
$string 
'hEllO woRLD';

$lower strtolower($string);
$upper strtoupper($string);

echo 
$lower '<br />';
echo 
$upper;

?>

This outputs:

hello world
HELLO WORLD

Note that the functions return the transformed string and do not output it on their own

Altering first letter of a string

The functions lcfirst and ucfirst convert the first letter of strings to lowercase and all uppercase respectively:

<?
$lower 
lcfirst('Hello World');
$upper ucfirst('hello world');

echo 
$lower '<br />';
echo 
$upper;

?>

This outputs:

hello World
Hello world

NOTICE: lcfirst is only available in PHP 5.3.0 and above

Transforming words in a string

The function ucwords converts the first letter of every word in a string to uppercase:

<?
$upper 
ucwords('hello world');

echo 
$upper;

?>

This will output:

Hello World

There isn't currently a lcwords function.