PHP Strings
Controlling Case
Problem
You need to capitalize, lowercase, or otherwise modify the case of letters in a string. Forexample, you want to capitalize the initial letters of names but lowercase the rest.
Solution
Example Capitalizing letters
print ucwords("the prince of wales");
Example prints:
How do you do today?
The Prince Of Wales
Example Changing case of strings
print strtoupper("i'm not yelling!");
print strtolower('<A HREF="one.php">one</A>');
Example prints:
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');
This prints:
Monkey face1 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:
print ucwords('1 monkey face');
print ucwords("don't play zone defense against the philadelphia 76-ers");
This prints:
1 Monkey FaceDon'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. Because 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:
print ucfirst('macWorld says I should get an iBook');
print ucwords('eTunaFish.com might buy itunaFish.Com!');
This prints:
MacWorld says I should get an iBook
ETunaFish.com Might Buy ItunaFish.Com!
The functions strtolower() and strtoupper() work on entire strings, not just indi‐
vidual characters. All alphabetic characters are changed to lowercase by strtolow
er() and strtoupper() changes all alphabetic characters to uppercase:
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.
No comments:
Post a Comment