Capitalization In Strings
Posted by Pete | Posted in PHP Beginners | Posted on 12-11-2009-05-2008
0
Manipulating strings for use with capitals is a simple job in PHP as there are 5 functions built in to help you with this task. strtoupper, strtolower, ucwords, ucfirst and lcfirst. In this tutorial I will show you how to use them and examples included.
strtoupper
strtoupper will capitalize all letters in the string given.
<?php $string = "hello my name is bob."; echo "Old: " . $string . "<br />"; echo "New: " . strtoupper($string); // HELLO MY NAME IS BOB. ?>
This could be used to create an emphasis on a important point such as a title etc.
Now we will move onto strtolower.
strtolower
strtolower is the opposite to strtoupper. strtolower makes all characters in a string to lowercase.
<?php $string = "PK-TUTS HAS THE BEST TUTORIALS."; echo "Old: " . $string . "<br />"; echo "New: " . strtolower($string); // pk-tuts has the best tutorials. ?>
As you can now see all characters are now in the lower case. This can be great if there are lots of capitals in a string may save time rather manually lowering the case.
ucwords
ucwords makes the first letter of every word into a uppercase letter.
<?php $string = "uPPER cASE iS bEST."; echo "Old: " . $string . "<br />"; echo "New: " . ucwords($string); // UPPER CASE IS BEST. ?>
ucfirst
ucfirst is similar to the function ucwords but ucfirst only changes the first letter of the first word in the string.
<?php $string = "uPPER cASE iS bEST."; echo "Old: " . $string . "<br />"; echo "New: " . ucfirst($string); // UPPER cASE iS bEST. ?>
lcfirst
lcfirst does the same function as ucfirst but in reverse so makes the first letter of the first word of the string to lower case.
<?php $string = "Lower Case Is Best."; echo "Old: " . $string . "<br />"; echo "New: " . lcfirst($string); // UPPER cASE iS bEST. ?>
So that’s it there is several basic functions that are built in to PHP. If you have any questions or feedback please leave a comment.


