PHP has some useful functions for dealing with capital letters in string variables. You can make a string all uppercase or lowercase. You can make only the first letter a capital, as in a name, or every other letter a capital for a title or headline.
- strtoupper() – Make a string all uppercase, as in “I CAN HAS CHEEZBURGER?”
- strtolower() – The reverse of strtoupper, removes all capitals.
- ucwords() – Capitalizes the first letter of each word.
- ucfirst() – Capitalized the first letter of the string. Perfect for displaying user names, as they are generally all lowercase.
Each function has a multitude of uses. I’ve found strtolower() to be particularly useful. It works well when you’re generating URLs. I like having URLs be all lowercase, so in a situation where data is being stored to be retrieved with a user-set URL (e.g. domain.com/script/user-submitted-title/) you can run a strtolower() on the submitted item title to make it all lowercase. Then you just need to urlencode() it.
How about a more complicated trick? Suppose a site like YouTube wanted to enforce correct capitalization in their comments. The general idea is simple: Capitalize the starting letter in each sentence. So you first split the comment into an array of sentences, capitalize each, and merge them back together.
<?php
$comment = "lol. i'm too cool to press the shift key. don't forget to visit my myspace page for more cool writin like this!";
$sentences = explode('. ', $comment);
$counter = 0;
foreach ($sentences as $sentence) {
$sentences[$counter] = ucfirst($sentence);
$counter++;
}
$fixed = implode('. ', $sentences);
echo $fixed;
?>
This should return Lol. I'm too cool to press the shift key. Don't forget to visit my myspace page for more cool writin like this!
It’s a very simple example, and it won’t work with exclamation points or question marks. (And let’s face it, most of the badly-written comments on YouTube don’t have any punctuation either!) It demonstrates the power of PHP’s string processing functions very well though.