ucwords() to convert a string to title case in PHP

by jim.mayes - March 22nd, 2008 (add comment)

I enjoy the challenge of solving a problem as much as the next guy, but sometimes it seems that PHP programmers have a tendency to apply great ingenuity in creating complex solutions for a fairly simple problem that actually already has a very simple solution. What's more, these bits of code (we'll call them "better mouse traps") usually end up posted on a blog someplace to be picked up and spread into countless people's applications.

have a look at this function I stumbled upon today...

PHP:
  1. function  titleCase($string)  {
  2.         $len=strlen($string);
  3.         $i=0;
  4.         $last= "";
  5.         $new= "";
  6.         $string=strtoupper($string);
  7.         while  ($i<$len):
  8.                 $char=substr($string,$i,1);
  9.                 if  (ereg( "[A-Z]",$last)):
  10.                         $new.=strtolower($char);
  11.                 else:
  12.                         $new.=strtoupper($char);
  13.                 endif;
  14.                 $last=$char;
  15.                 $i++;
  16.         endwhile;
  17.         return($new);
  18. };

That's a function that takes a string, retrieves it's length, converts it to upper case, then loops through the characters in the string to detect word breaks and then convert to lower case individually each character that isn't the start of a word. The author proposed this as a function to capitalizing strings for titles. It's a pretty solid little function which displays a good bit of ingenuity in the understanding and use of some slightly more advanced aspects of PHP. Hell, it's actually pretty slick! And I found this same function posted on several websites.

The thing is...

PHP:
  1. echo ucwords('there is a PHP native function to upper case words in a string!');

...and that function is ucwords()

Leave a Reply