PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<ucfirstvprintf>
view the version of this page
Last updated: Sun, 02 May 2004

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).

Esempio 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!
?>

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



add a note add a note User Contributed Notes
ucwords
kreulis at kreulis dot com
20-May-2004 09:39
<?Php
$city
="VACARIA brazil";
ucwords(strtolower($city)); //var city = Vacaria Brazil
?>
babel - nospamplease - sympatico - ca
11-Feb-2004 02: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.
Justin at gha dot bravepages dot com
05-Apr-2003 11:39
Here's my swing on things

function limited_ucfirst($text, $min_word_len = 4,
                             $always_cap_first = true,
                             $exclude =
Array("of","a","the ","and","an",
"or","nor","but","is",
"if","then","else","when","up",
"at","from","by","on",
"off","for","in","out","over",
"to","into", "with")) {

 // Allows for the specification of the minimum length
 //  of characters each word must be in order to be capitalized

 // Make sure words following punctuation are capitalized
 $text = str_replace(
Array("(", "-", ".", "?", ",",":","[",";","!"),
Array("( ", "- ", ". ", "? ", ", ",": ","[ ","; ","! "), $text);

 $words = explode (" ", strtolower($text));
 $count = count($words);
 $num = 0;

while ($num < $count) {
   if (strlen($words[$num]) >= $min_word_len
       && array_search($words[$num], $exclude) === false)
     $words[$num] = ucfirst($words[$num]);
   $num++;
 }

 $text = implode(" ", $words);
 $text = str_replace(
Array("( ", "- ", ". ", "? ", ", ",": ","[ ","; ","! "),
Array("(", "-", ".", "?", ",",":","[",";","!"), $text);

 // Always capitalize first char if cap_first is true
if ($always_cap_first) {
   if (ctype_alpha($text[0]) && ord($text[0]) <= ord("z")
     && ord($text[0]) > ord("Z"))
     $text[0] = chr(ord($text[0]) - 32);
}

 return $text;
}

Thanks to mgm and un-thesis for their last two posts.  It was helpful in fine tuning this funcion.
un-thesis at wakeup-people dot com
21-Feb-2003 06:53
This will capitalize words beginning with every major English punctuation symbol.  You can add your own (foreign) symbols here as well :-)

$words = "What?No delimiters,shit happens;all the time!here:this--solves (definately) [many more] all problems.";
$words = str_replace(Array("(", "-", ".", "?", ",",":","[",";","!"), Array("( ", "- ", ". ", "? ", ", ",": ","[ ","; ","! "), $words);
$words = ucwords(strtolower($words));
$words = str_replace(Array("( ", "- ", ". ", "? ", ", ",": ","[ ","; ","! "), Array("(", "-", ".", "?", ",",":","[",";","!"), $words);
print "$words\n";
mgm at starlingtech dot com
21-Feb-2003 06: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 10: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
ulderico at maber dot com dot br
30-Dec-2002 06:56
those who want to capitalise the first letters of the longer words (which can be very helpful in Latin languages as Portuguese, Italian or Spanish)... I've made this handy function... It captalise only the longer words... And the user can set how long is a SMALLWORD.

$string = "isto um teste ... o e o um no devem ficar maisculas";

echo ucfirst($string)."<BR>";
echo ucwords($string)."<BR>";
echo uclongwords($string);

function uclongwords($string){

       $strlen      = strlen($string);
       $cursor      = 0;
       $wordlen      = 0;
       $first_letter = 0;
       $i            = 0;
       DEFINE("SMALLWORD", 3);

       for($i = 0; $i < $strlen; ++$i){

             if($string{$i} != " "){
                    
                     if($wordlen == 0)
                             $first_letter = $i;
                     if(++$wordlen > SMALLWORD){
                             $return{$first_letter} = strtoupper($return{$first_letter});
                     }

             }else{
                     $wordlen = 0;
             }

             $return .= $string{$i};

       }

       return($return);
}

should produce

Isto um teste ... o e o um no devem ficar maisculas
Isto Um Teste ... O E O Um No Devem Ficar Maisculas
Isto um Teste ... o e o um no Devem Ficar Maisculas
deepdene at email dot com
10-Dec-2002 05: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 09: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 04: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 02: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="xxxxx" will be "XxxXxx" 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 01: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!
cowbert at hotmail dot com
20-Aug-2002 03:48
Articles: the, a, an
Conjunctions: and, or, nor, but
Preposition: of
evan at coeus hyphen group dot com
10-Feb-2002 01:55
The following blurb (should be all one line...) will capitalize all words except for "of", "a", "the", and "and" (unless they are the first word, in which case they will be capitalized.)

trim(ucfirst(str_replace(Array("Of ","A ","The ","And "),Array("of ","a ","the ","and "),ucwords(strtolower($str)))));

Unfortunately, it won't work w/ acronyms ("U.S.A." comes out "U.s.a."- but that is a problem w/ ucwords.) There aren't any articles im missing, are there???
19-Jan-2002 12: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
04-Nov-2001 01: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 04: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";
paul at webkromatic dot com
10-Jul-2001 11:22
This is basically the same as Jim Thome's script above but it tests for numbers also.  So if you have 3rd it won't end up 3Rd.

function ucase_words($txt)
   {
   $i = 0;
   $txt = strtolower($txt);
   while ($i < strlen($txt))
   {
         if (ord(substr($txt, $i, 1)) > 96 && ord(substr($txt, $i, 1)) < 123) // any lower case letter
         {
             if ($i == 0)//first letter should be upper case
             {
             $newtxt .= strtoupper(substr($txt, $i, 1));
             } else {//check for preceding letter or number, so things like 3rd wont be 3Rd
                   if ((ord(substr($txt, $i - 1, 1)) > 96 && ord(substr($txt, $i - 1 , 1)) < 123) || (ord(substr($txt, $i - 1, 1)) > 47 && ord(substr($txt, $i - 1, 1)) < 58))
                   {
                   $newtxt .= substr($txt, $i, 1);
                   } else {
                   $newtxt .= strtoupper(substr($txt, $i, 1));
                   }
               }
             } else {
             $newtxt .= substr($txt, $i, 1);
             }
   $i++;
   }
   return($newtxt);
}

Paul
Paul@webkromatic.com
jthome at fcgov dot com
16-May-2001 11:37
This function will change the first letter of any words to uppercase. Any letter that doesn't have another letter in front of it is considered a word, which eliminates the need to care about a delimiter. (I avoid regular expressions except when I have to deal with large amounts of text.)

function ucase_words($txt)
{
$i = 0;
$txt = strtolower($txt);
while ($i < strlen($txt))
{
if (ord(substr($txt, $i, 1)) > 96 && ord(substr($txt, $i, 1)) < 123) // any lower case letter
{
if ($i == 0)//any first letter should be upper case
{
$newtxt .= strtoupper(substr($txt, $i, 1));
} else {//check for preceding letter
if (ord(substr($txt, $i - 1, 1)) > 96 && ord(substr($txt, $i - 1 , 1)) < 123)
{
$newtxt .= substr($txt, $i, 1);
} else {
$newtxt .= strtoupper(substr($txt, $i, 1));
}
}
} else {
$newtxt .= substr($txt, $i, 1);
}
$i++;
}

return($newtxt);
}


Hope this helps someone.

Jim Thome
jthome@fcgov.com
http://fcgov.com
mistcat at mistcat dot com
28-Mar-2001 09: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 11: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;
joerg at krause dot net
27-Dec-2000 04:06
None of the examples above recognizes characters normally used as delimiters. The following uses a regular expression, which is easy to extend, to create an array with the parts of a text. Then it runs the ucfirst-function for each part an implode the array:

$text = "What?No delimiters,shit happens here.this solves all problems.";
preg_match_all("/(\w+[,. ?])+/U", $text, $words);
foreach($words[0] as $part) $uwords[] = ucfirst($part);
$text = implode("", $uwords);
echo $text;

Joerg Krause
www.php.comzept.de
www.joergkrause.de/krause
Rodney_Hampton at yahoo dot com
25-Jul-2000 05:20
I've had trouble with the ucwords command.  I have found that the following is a reasonable substitute where crumb is the string that you want to make the words upper case.
<pre>
$nibble=explode (" ", $crumb);
$count=count($nibble);
$num=0;
while ($num<$count){
$nibble[$num]=ucfirst($nibble[$num]);
$num++;
}
$crumb=implode(" ",$nibble);
</pre>
bobo at ii dot nl
17-Jul-2000 05: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);

<ucfirstvprintf>
 Last updated: Sun, 02 May 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: Italia OnLine S.p.a.
Last updated: Fri May 21 04:11:23 2004 CEST