Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

1.6. Controlling Case

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.

Solution

Use ucfirst( ) or ucwords( ) to capitalize the first letter of one or more words:

print ucfirst("how do you do today?");
print ucwords("the prince of wales");
How do you do today?
               The Prince Of Wales

Use strtolower( ) or strtoupper( ) to modify the case of entire strings:

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

Discussion

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

print ucfirst('monkey face');
print ucfirst('1 monkey face');
Monkey face
               1 monkey face

Note that the second line of output is not “1 Monkey face”.

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

print ucwords('1 monkey face');
print ucwords("don't play zone defense against the philadelphia 76-ers");
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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata