Transforming Capital Letters With PHP

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.

  • http://ineeddiscipline.com/2008/07/04/19-blog-review-networks/ Dean Saliba

    This is great. I've been looking for a piece of code or a plugin that could accomplish this option for my blogs.

    When I write I normally get so carried away that I tend to forget to capitalise words and then have to go back oveer the article.

  • Mike

    How do I convert a string of all capital letters to a more pleasant to read format?

  • Victoria

    Hi!

    I can’t get the capitalize first letter in sentence to work with utf-8 encoded websites, would very much appreciate if you knew anything more on this! :)
    //Victoria