Wednesday, May 18, 2016

PHP String Capitalization Functions

If youve ever wanted to manipulate the capitalization of your PHP strings, then this lesson will be quite helpful to you. PHP has three primary capitalization related functions: strtoupper, strtolower and ucwords. The function names are pretty self-explanatory, but why they are useful in programming might be new to you.

Converting a String to Upper Case - strtoupper

The strtoupper function takes one argument, the string you want converted to upper case and returns the converted string. Only letters of the alphabet are changed, numbers will remain the same.

PHP Code:

$originalString = "String Capitalization 1234";
$upperCase = strtoupper($originalString);
echo "Old string - $originalString <br />";
echo "New String - $upperCase";

Display:

Old string - String Capitalization 1234
New String - STRING CAPITALIZATION 1234

One might use this function to increase emphasis of a important point or in a title. Another time it might be used with a font that looks very nice with all caps to fit the style of the web page design.

A more technical reason would be to convert two strings you are comparing to see if they are equal. By converting them to the same capitalization you remove the possibility that they wont match simply because of different capitalizations.

Converting a String to Lower Case - strtolower

The strtolower function also has one argument: the string that will be converted to lower case.

PHP Code:

$originalString = "String Capitalization 1234";
$lowerCase = strtolower($originalString);
echo "Old string - $originalString <br />";
echo "New String - $lowerCase";

Display:

Old string - String Capitalization 1234
New String - string capitalization 1234

Capitalizing the First Letter - ucwords

Titles of various media types often capitalize the first letter of each word and PHP has a time-saving function that will do just this.

PHP Code:

$titleString = "a title that could use some hELP";
$ucTitleString = ucwords($titleString);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";

Display:

Old title - a title that could use some hELP
New title - A Title That Could Use Some HELP

Notice that the last word "hELP" did not have the capitalization changed on the letters that werent first, they remained capitalized. If you want to ensure that only the first letter is capitalized in each word of your title, first use the strtolower function and then the ucwords function.

PHP Code:

$titleString = "a title that could use some hELP";
$lowercaseTitle = strtolower($titleString);
$ucTitleString = ucwords($lowercaseTitle);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";

Display:

Old title - a title that could use some hELP New title - A Title That Could Use Some Help