search for in the  
<ucfirstvfprintf>
Last updated: Thu, 19 May 2005

ucwords

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ucwords --  Uppercase the first character of each word in a string

Description

string ucwords ( string str )

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Example 1. ucwords() example

<?php
$foo
= 'hello world!';
$foo = ucwords($foo);            // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);            // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Note: This function is binary-safe.

See also strtoupper(), strtolower() and ucfirst().



User Contributed Notes
ucwords
j dot ravier at free dot fr
21-Mar-2005 06:50
For western accentuated letters:
You can use a simple preg_replace expression to replace ucwords if you have only the ascii characters converted.

<?php
function ucwordsw($value) {
return
preg_replace('/(^|[^A-Za-z0-9_\xC0-\xFF])([a-z\xE0-\xFF])/e', '"$1".chr(ord("$2")-32)', $value);
}
?>
- Redefinition of '\w' (a word character) : [A-Za-z0-9_\xC0-\xFF]
includes the western accentuated letters, lower or upper case.
 - Redefinition of '\W' (a non word character) :
^|[^A-Za-z0-9_\xC0-\xFF]
 -> either the beginning (^) of the searched string or any non ([^...]} newly defined 'word' character

So any lower case letter ($2),
 - accentuated ([\xE0-\xFF]) or not ([a-z]),
 - and following a non word character ($1)
will be uppercased (chr(ord('...')-32)
(took that bit from a post from Ansis [ataols in latnet point lv] (27-Jan-2004 11:40) on the strtoupper function page http://www.php.net/manual/fr/function.strtoupper.php).
igua no-spam at coveruniverse dot com
08-Mar-2005 06:30
The code posted by neil doesn't fully do what is wanted. Try adding some more question marks at the end and it will return a not wanted string.

Below code will uppercase all your words regardless of the delimiter.

<?php
$text
= "What?No 'delimiters',shit \"happens\" here.this solves all problems???";
preg_match_all('/[A-Za-z]+|[^A-Za-z]+/', $text, $data);
for (
$i = 0; $i < count($data[0]); $i++) {
 
$data[0][$i] = ucfirst($data[0][$i]);
}
$text = implode("", $data[0]);
print
$text;
?>
theonly dot mcseven at gmx dot net
24-Jan-2005 02:55
Unfortunately, this function will not convert uppercased strings (sat here a few hours before realising that). So before ucwords-ing a string, make sure to lowercase it first:
$my_true_ucwords_string = ucwords(strtolower($my_test_string));
arjini at gmail dot com
23-Jan-2005 02:20
Not so much ucwords() related as it is capital letter related. I often use camel casing (as do wikis), I needed a reason to reverse the camel casing.

function unCamelCase($str){
   $bits = preg_split('/([A-Z])/',$str,false,PREG_SPLIT_DELIM_CAPTURE);
   $a = array();
   array_shift($bits);
   for($i = 0; $i < count($bits); ++$i)
       if($i%2)
           $a[] = $bits[$i - 1].$bits[$i];
   return $a;
}

print_r(unCamelCase('MyFancyCamelCasedWord'));

Array
(
   [0] => My
   [1] => Fancy
   [2] => Camel
   [3] => Cased
   [4] => Word
)
joshuamallory at yahoo dot com
14-Nov-2004 10:08
If you want to format a string like...

<?php
   $string
= "computer programming/repair";
   print
ucwords($string);
?>

Output: Computer Programming/repair

Notice the word after the slash (Programming/repair) isn't capitalized. To fix this, use CSS...

<?php
   $string
= "computer programming/repair";
   print
'<p style="text-transform:capitalize">';
   print
ucwords($string);
   print
'<p>';
?>
babel - nospamplease - sympatico - ca
10-Feb-2004 10:26
Correction to the code of firewire at itsyourdomain dot com:

preg_replace_callback('/\b(\w)(\w+)?/',
   create_function('$a',
   'return strtoupper($a[1]) . ((sizeof($a) > 2 ) ? 
       strtolower($a[2]) : "");'),
   'p.s.: hello.this is my string.');

Will work with punctuation as well as spaces.
mgm at starlingtech dot com
21-Feb-2003 02:30
Here's a modified version of the earlier example for Title Case that uses a more complete list of prepositions, conjunctions, and articles that works well for me. (one big line, or break up as necessary)

$line = trim(ucfirst(str_replace(Array("Of ","A ","The ","And ","An ", "Or ", "Nor ","But ","If ","Then ","Else ","When ","Up ","At ","From ","By ","On ","Off ","For ","In ","Out ","Over ","To "),Array("of ","a ","the ","and ","an ","or ","nor ","but ","if ","then ","else ","when ","up ","at ","from ","by ","on ","off ","for ","in ","out ","over ","to "),ucwords(strtolower($line)))));

There's probably a way to shorten this.
Edemilson Lima - pulstar at mail dot com
11-Feb-2003 06:55
Not everything must be capitalized. Many times we need words to be in lowercase or all in uppercase. When a word have numbers for example, it may be a special code that must not be changed. The function below is my best effort to produce an human-like capitalization of strings. Try it for yourself and take your own conclusions. It is automatic and also works with some foreign characters. The second optional parameter when set to zero produce strings like ucfirst() function (by default it generate strings like ucwords() function).

function finecase($str,$type="words") {
   $arr=explode(" ",$str);
   foreach($arr as $key=>$value) {
       if(eregi("^[AEIOUÀ-ÿ]{1,2}$",$value)) {
           $value=strtolower($value);
       }
       if(eregi("^[B-DF-HJ-NP-TV-Z][AEIOUÀ-ÆÈ-æè-ÿ]$",$value)) {
           $value=strtolower($value);
       }
       if(eregi("^[AEIOUÀ-ÿ][B-DF-HJ-NP-TV-Z]$",$value)) {
           $value=strtolower($value);
       }
       if(eregi("^[A-ZÀ-ÿ-]{3,50}$",$value)) {
           if($type=="words" or !$key) {
               $value=ucfirst(strtolower($value));
           } else {
               $value=strtolower($value);
           }
       } elseif(eregi("^.{3,50}$",$value)) {
           if($type=="words" or !$key) {
               $value=ucfirst($value);
           }
       }
       if(eregi("^[A-ZÀ-ÿ]+([!-/:-@\-`{-~]+[A-ZÀ-ÿ]+)+$", $value)) {
           if($type=="words" or !$key) {
               $value=ucwords(strtolower($value));
           } else {
               $value=strtolower($value);
           }
       }
       if(eregi("^[A-ZÀ-ÿ]{3,50}(,|\.+)$",$value)) {
           if($type=="words" or !$key) {
               $value=ucfirst(strtolower($value));
           } else {
               $value=strtolower($value);
           }
       }
       if(eregi("^[b-df-hj-np-tv-zçñ]+$",$value)) {
           $value=strtoupper($value);
       }
       if(eregi("^.+$",$value) and ereg("^.*(\.+|\?|!|;)$",$arr[$key-1])) {
           $value=ucfirst($value);
       }

       $arr[$key]=$value;
   }
   $str=join(" ",$arr);
   return $str;
}

Regards,
Edemilson Lima
deepdene at email dot com
10-Dec-2002 01:20
A function knowing about name case (i.e. caps on McDonald etc)

function name_case($name)
{
   $newname = strtoupper($name[0]);   
   for ($i=1; $i < strlen($name); $i++)
   {
       $subed = substr($name, $i, 1);   
       if (((ord($subed) > 64) && (ord($subed) < 123)) ||
           ((ord($subed) > 48) && (ord($subed) < 58)))
       {
           $word_check = substr($name, $i - 2, 2);
           if (!strcasecmp($word_check, 'Mc') || !strcasecmp($word_check, "O'"))
           {
               $newname .= strtoupper($subed); 
           }
           else if ($break)
           {
              
               $newname .= strtoupper($subed);
           }
           else     
           {
               $newname .= strtolower($subed);
           }
             $break=0;
       }
       else
       {
           // not a letter - a boundary
             $newname .= $subed;
           $break=1;
       }
   }   
   return $newname;
}
firewire at itsyourdomain dot com
19-Nov-2002 05:13
For those that want to capitalize based on a regular expression.
print preg_replace_callback('/(\s|^)[a-z]/', create_function('$a', 'return strtoupper($a[0]);'), 'hello this is my string');

This is a quick untested example.
anton at titov dot net
25-Sep-2002 12:56
for those, who not avoid regular expressions, solution of discussed problem:

$text=preg_replace('/(\W)(\w)/e', '"\\1".strtoupper("\\2")', ucfirst(strtolower($text)));
fille at fukt dot bth dot se
27-Aug-2002 10:04
[Editor's note: For details on the bug see
http://bugs.php.net/bug.php?id=14655]

This function has a bug, and while waiting for the bug fix, here is a work-around pice of code.

When using international letters, you will get into troubles with the ucwords() function.

Example:

$string="xxxöxx" will be "XxxöXxx" after beeing processed by ucwords().

To get around it, I wrote some extra code that checks the string once more, and lowercases all letters that is not in the beginning of a word.

$string=ucwords($string);
//Bugfix from here on
for($i=0;$i<strlen($string);$i++)
   if((ctype_upper($string[$i]) &&( $string[$i-1]==" " || $i==0 ))!=TRUE)
       $string[$i]=strtolower($string[$i]);

Thia code is also an optional way of doing the same work on a string that is totally UPPERCASE.
27-Aug-2002 09:20
Beware of language when using this function to collate personal names! This may not work with some languages and this depends on the current locale!
So it's best to simply use strtoupper() or strtolower(strtoupper()) to collate names for searches in a database. Avoid using strtolower() directly, as it won't collate some characters like the german 'ß' into 'ss'.
Capitalizing names is very language dependant: don't do it on address fields such as city names. Prefer uppercasing, or keep the original case if the string must be displayed to a user!
18-Jan-2002 08:14
This seems to be what people want:

function uc_all($string) {
   $temp = preg_split('/(\W)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
   foreach ($temp as $key=>$word) {
       $temp[$key] = ucfirst(strtolower($word));
   }
   return join ('', $temp);
}

[ed note: fixed the code to be correct]
Julienc at psychologie-fr dot com
03-Nov-2001 09:06
Its still possible to clean a bit more the previous sample:

$string=strtolower($string); $break=true;
for ($i=0; $i < strlen($string); $i++) { $subed=$string[$i];
if (((ord($subed) > 64) && (ord($subed) < 123)) || ((ord($subed) > 48) && (ord($subed) < 58))) {
if ($break) { $string[$i] = strtoupper($subed); }
$break=false; } else { $break=true; }
}

- Julien
mlong at spammer=0 dot infoave dot net
20-Aug-2001 12:38
An evolution of the previous (a little more compact I think):

$name="ReaLLY s'CREWED Name, JR.";
$break=1;
for ($i=0; $i < strlen($name); $i++)
{
 $subed=substr($name,$i,1);
 # if its a letter or num
 if (((ord($subed) > 64) && (ord($subed) < 123)) ||
     ((ord($subed) > 48) && (ord($subed) < 58)))
 {
  if ($break) { $newname .= strtoupper($subed); }
  else        { $newname .= strtolower($subed); }
  $break=0;
 }
 else
 {
  # not a letter - a boundary
  $newname .= $subed;
  $break=1;
 }
}
echo "$newname\n";
mistcat at mistcat dot com
28-Mar-2001 04:00
Actually that code would work if you changed this line:
$words[0][] = $lastword;
to
$words[0][] = $lastword[0];
neil at no-spam-ents24 dot com
21-Mar-2001 07:10
The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:

$text = "What?No delimiters,shit happens here.this solves all problems.";
preg_match_all("/(\w+[,. ?])+/U", $text, $words);
preg_match("/(\w+)$/", $text, $lastword);
$words[0][] = $lastword;
foreach($words[0] as $part) $uwords[] = ucfirst($part);
$text = implode("", $uwords);
echo $text;
bobo at ii dot nl
17-Jul-2000 01:42
Mildly annoying, only spaces are considered whitespace by this function. So words right after linebreaks do not get capitalized. An explode/implode can help here.

$temp = explode ("\n", $capthis);
array_walk (&$temp, ucwords);
$capthis = implode ("\n", $temp);

<ucfirstvfprintf>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT