PHP Strings Primer - Capitalization
(Page 13 of 37 )
The two functions, 'ucfirst()' and 'ucwords()', provide very similar functionality. Both take a string and apply some level of capitalization to it. The difference is that 'ucfirst()' only capitalizes the first character of a string, while 'ucwords()' capitalizes the first character of every word in a string. Both of these functions are generally used for display purposes only.
Using the 'ucfirst()' function can come in handy when you have a string that you want to display, and you want to make sure that the first character is capitalized. It is a very simple function to use, as shown by this example.
<?php $str = 'this is a sentence.'; echo ucfirst ($str); ?> |
This would output:
It is worth noting that the ucfirst() function only touches the first character in a string. If a string has capital letters in it, they will remain unmodified. Let's look at an example to illustrate this point.
<?php $str = 'this Sentence HAS some other letters capitalized.'; echo ucfirst ($str); ?> |
Output:
This Sentence HAS some other letters capitalized. |
The 'ucwords()' function is frequently used to properly capitalize names, titles, and headlines. It is worth noting that this function is far from perfect however. In order to demonstrate the shortcoming of the 'ucwords' function, let us look at some examples. Each example will be followed immediately by its actual output and hoped for output.
<?php echo ucwords ('of mice and men'); ?> |
Actual:
Wanted:
<?php echo ucwords ('john o'conner'); ?> |
Actual:
Wanted:
<?php echo ucwords ('TOM SAWYER'); ?> |
Actual:
Wanted:
This last example is easily corrected by using the 'strtolower' function.
<?php echo ucwords (strtolower ('TOM SAWYER')); ?> |
The other examples are just common pitfalls of the ucwords function. Other than designing your own function to capitalize the words correctly, there is no way to fix the problem.
Next: Reversing strings >>
More Programming Basics Articles
More By Matt Wade