Recipe 1.7. Controlling Case

1.7.1. Problem

You need to capitalize , lowercase, or otherwise modify the case of letters in a string. For example, you want to capitalize the initial letters of names but lowercase the rest.

1.7.2. Solution

Use ucfirst( ) or ucwords( ) to capitalize the first letter of one or more words, as shown in Example 1-25.

Capitalizing letters

<?php print ucfirst("how do you do today?"); print ucwords("the prince of wales"); ?>

Example 1-25 prints:

How do you do today? The Prince Of Wales

Use strtolower( ) or strtoupper( ) to modify the case of entire strings, as in Example 1-26.

Changing case of strings

print strtoupper("i'm not yelling!"); // Tags must be lowercase to be XHTML compliant print strtolower('<A HREF="one.php">one</A>');

Example 1-26 prints:

I'M NOT YELLING! <a href="one.php">one</a>

1.7.3. Discussion

Use ucfirst( ) to capitalize the first character in a string:

<?php print ucfirst('monkey face'); print ucfirst('1 monkey face'); ?>

This prints:

Monkey face 1 monkey face

Note that the second phrase is not "1 Monkey face."

Use ucwords( ) to capitalize the first character of each word in a string:

<?php print ucwords('1 monkey face'); print ucwords("don't play zone defense against the philadelphia 76-ers"); ?>

This prints:

1 Monkey Face Don't Play Zone Defense Against The Philadelphia 76-ers

As expected, ucwords( ) doesn't capitalize the "t" in "don't." But it also doesn't capitalize the "e" in "76-ers." For ucwords( ), a word is any sequence of nonwhitespace characters that follows one or more whitespace characters. Since both ' and - aren't whitespace characters, ucwords( ) doesn't consider the "t" in "don't" or the "e" in "76-ers" to be word-starting characters.

Both ucfirst( ) and ucwords( ) don't change the case of non-first letters:

<?php print ucfirst('macWorld says I should get an iBook'); print ucwords(' might buy itunaFish.Com!'); ?>

This prints:

MacWorld says I should get an iBook Might Buy ItunaFish.Com!

The functions strtolower( ) and strtoupper( ) work on entire strings, not just individual characters. All alphabetic characters are changed to lowercase by strtolower( ) and strtoupper( ) changes all alphabetic characters to uppercase:

<?php print strtolower("I programmed the WOPR and the TRS-80."); print strtoupper('"since feeling is first" is a poem by e. e. cummings.'); ?>

This prints:

i programmed the wopr and the trs-80. "SINCE FEELING IS FIRST" IS A POEM BY E. E. CUMMINGS.

When determining upper- and lowercase, these functions respect your locale settings.

1.7.4. See Also

For more information about locale settings, see Chapter 19; documentation on ucfirst( ) at, ucwords( ) at, strtolower( ) at, and strtoupper( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: