Documentation on ucwords

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

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 any character listed in the delimiters parameter (By default these are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Usage, params, and more on ucwords

string ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] )

str The input string. delimiters The optional delimiters contains the word separator characters.

Returns the modified string.

Notes and warnings on ucwords

Basic example of how to use: ucwords

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

Example #2 ucwords() example with custom delimiter

<?php
$foo 
'hello|world!';
$bar ucwords($foo);             // Hello|world!

$baz ucwords($foo"|");        // Hello|World!
?>

Other code examples of ucwords being used

My quick and dirty ucname (Upper Case Name) function.

<?php
//FUNCTION

function ucname($string) {
   
$string =ucwords(strtolower($string));

    foreach (array(
'-', '\'') as $delimiter) {
      if (
strpos($string, $delimiter)!==false) {
       
$string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return
$string;
}
?>
<?php
//TEST

$names =array(
 
'JEAN-LUC PICARD',
 
'MILES O\'BRIEN',
 
'WILLIAM RIKER',
 
'geordi la forge',
 
'bEvErly CRuSHeR'
);
foreach (
$names as $name) { print ucname("{$name}\n"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>

You can add more delimiters in the for-each loop array if you want to handle more characters.

Para formatar nomes em pt-br:

<?php

   
function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("de", "da", "dos", "das", "do", "I", "II", "III", "IV", "V", "VI"))
    {
       
/*
         * Exceptions in lower case are words you don't want converted
         * Exceptions all in upper case are any words you don't want converted to title case
         *   but should be converted to upper case, e.g.:
         *   king henry viii or king henry Viii should be King Henry VIII
         */
       
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
        foreach (
$delimiters as $dlnr => $delimiter) {
           
$words = explode($delimiter, $string);
           
$newwords = array();
            foreach (
$words as $wordnr => $word) {
                if (
in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                   
// check exceptions list for any words that should be in upper case
                   
$word = mb_strtoupper($word, "UTF-8");
                } elseif (
in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                   
// check exceptions list for any words that should be in upper case
                   
$word = mb_strtolower($word, "UTF-8");
                } elseif (!
in_array($word, $exceptions)) {
                   
// convert to uppercase (non-utf8 only)
                   
$word = ucfirst($word);
                }
               
array_push($newwords, $word);
            }
           
$string = join($delimiter, $newwords);
       }
//foreach
      
return $string;
    }

?>

Usage:

<?php
    $s
= 'SÃO JOÃO DOS SANTOS';
   
$v = titleCase($s); // 'São João dos Santos'
?>

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;
?>

ucwords for UTF-8 strings:

<?php
function mb_ucwords($str) {
   
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
    return (
$str);
}
?>

Some recipes for switching between underscore and camelcase naming:

<?php
// underscored to upper-camelcase
// e.g. "this_method_name" -> "ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);

// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);

// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>

Of course these aren't 100% symmetric.  For example...
  * this_is_a_string -> ThisIsAString -> this_is_astring
  * GetURLForString -> get_urlfor_string -> GetUrlforString

Features:
- multi byte compatible
- handles multiple delimiters

<?php
function ucwords_specific ($string, $delimiters = '', $encoding = NULL)
{
    if (
$encoding === NULL) { $encoding = mb_internal_encoding();}

    if (
is_string($delimiters))
    {
       
$delimiters str_split( str_replace(' ', '', $delimiters));
    }

   
$delimiters_pattern1 = array();
   
$delimiters_replace1 = array();
   
$delimiters_pattern2 = array();
   
$delimiters_replace2 = array();
    foreach (
$delimiters as $delimiter)
    {
       
$uniqid = uniqid();
       
$delimiters_pattern1[]   = '/'. preg_quote($delimiter) .'/';
       
$delimiters_replace1[]   = $delimiter.$uniqid.' ';
       
$delimiters_pattern2[]   = '/'. preg_quote($delimiter.$uniqid.' ') .'/';
       
$delimiters_replace2[]   = $delimiter;
    }

   
// $return_string = mb_strtolower($string, $encoding);
   
$return_string = $string;
   
$return_string = preg_replace($delimiters_pattern1, $delimiters_replace1, $return_string);

   
$words = explode(' ', $return_string);

    foreach (
$words as $index => $word)
    {
       
$words[$index] = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding).mb_substr($word, 1, mb_strlen($word, $encoding), $encoding);
    }

   
$return_string = implode(' ', $words);

   
$return_string = preg_replace($delimiters_pattern2, $delimiters_replace2, $return_string);

    return
$return_string;
}
?>

Params:
1. string: The string being converted
2. delimiters: a string with all wanted delimiters written one after the other e.g. "-'"
3. encoding: Is the character encoding. If it is omitted, the internal character encoding value will be used.

Example Usage:
<?php
mb_internal_encoding
('UTF-8');
$string = "JEAN-PAUL d'artagnan şŠ-òÀ-éÌ hello - world";
echo
ucwords_specific( mb_strtolower($string, 'UTF-8'), "-'");
?>

Output:
Jean-Paul D'Artagnan Şš-Òà-Éì Hello - World

In the function ucsmart() posted by ieure at php dot net on 04-Dec-2005 11:57, I found a similar problem in this function to what he found in igua's.

<?php
function ucsmart($text)
{
   return
preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                      
strtolower($text));
}
?>

"igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case."

Actually, it did end up changing the content for me (php 5.0.4) in the way that this function escapes a single quotation (apostrophe) in the MIDDLE of a word.

For example:

who's online?

Became:

Who\'s Online?

The fix is simple however, and merely requires fine-tuning the regular expression:

<?php
function ucsmart($text)
{
   return
preg_replace('/([^a-z\']|^)([a-z])/e', '"$1".strtoupper("$2")',
                      
strtolower($text));
}
?>

(note: while previewing this note before adding it, I am noticing php's website is not correctly displaying the change I made as I wrote it. After the first a-z in the expression, the single quotation should be escaped... If it isn't you will get a parse error! And apoligies if my text here is colored as php code; not my fault!)

This will not escape a single quotation mark which occurs in the middle of a word... Though, you may find that might need to add other characters inside the regular expression if you use other special characters inside your words and if you get funky output.

It's a great expression though! Simple, yet very powerful. Kudos!

Turkish character with the ucwords function...

<?php
function ucwords_tr($gelen){

 
$sonuc='';

 
$kelimeler=explode(" ", $gelen);

  foreach (
$kelimeler as $kelime_duz){

   
$kelime_uzunluk=strlen($kelime_duz);
   
$ilk_karakter=mb_substr($kelime_duz,0,1,'UTF-8');

    if(
$ilk_karakter=='Ç' or $ilk_karakter=='ç'){

     
$ilk_karakter='Ç';

    }elseif (
$ilk_karakter=='Ğ' or $ilk_karakter=='ğ') {

     
$ilk_karakter='Ğ';

    }elseif(
$ilk_karakter=='I' or $ilk_karakter=='ı'){

     
$ilk_karakter='I';

    }elseif (
$ilk_karakter=='İ' or $ilk_karakter=='i'){

     
$ilk_karakter='İ';

    }elseif (
$ilk_karakter=='Ö' or $ilk_karakter=='ö'){

     
$ilk_karakter='Ö';

    }elseif (
$ilk_karakter=='Ş' or $ilk_karakter=='ş'){

     
$ilk_karakter='Ş';

    }elseif (
$ilk_karakter=='Ü' or $ilk_karakter=='ü'){

     
$ilk_karakter='Ü';

    }else{

     
$ilk_karakter=strtoupper($ilk_karakter);

    }

   
$digerleri=mb_substr($kelime_duz,1,$kelime_uzunluk,'UTF-8');
   
$sonuc.=$ilk_karakter.kucuk_yap($digerleri).' ';

  }

 
$son=trim(str_replace('  ', ' ', $sonuc));
  return
$son;

}

function
kucuk_yap($gelen){

 
$gelen=str_replace('Ç', 'ç', $gelen);
 
$gelen=str_replace('Ğ', 'ğ', $gelen);
 
$gelen=str_replace('I', 'ı', $gelen);
 
$gelen=str_replace('İ', 'i', $gelen);
 
$gelen=str_replace('Ö', 'ö', $gelen);
 
$gelen=str_replace('Ş', 'ş', $gelen);
 
$gelen=str_replace('Ü', 'ü', $gelen);
 
$gelen=strtolower($gelen);

  return
$gelen;
}

echo
ucwords_tr('ŞEKardi ŞEMŞİYE ĞELENÖ ÖMER'); // Şekardi Şemşiye Ğelenö Ömer
echo ucwords_tr('şEKER iMSAK şÖLEN'); // Şeker İmsak Şölen

Recently i got a request from a client to make the first letter of any word in capital even they are separated by hyphen.

Eg : donzé pierre-yves      => Donzé Pierre-Yves
       joye-cagnard frédéric => Joye-Cagnard Frédéric

ucwords("donzé pierre-yves") can make it display
Donzé Pierre-yves but actually i need even the first letter of the second word to be in capital.

So in order to get this i have just written a function below and it works fine. But i hope there would be a better and easier way to do this if so kindly share.

<?php

$str
= "donzé pierre-yves";
echo
ucwordsHyphen($str); /*returns Donzé Pierre-Yves*/

function ucwordsHyphen($str){
                   
$converted_str = "";
                   
$str_array = explode(" ",$str);
                    foreach(
$str_array as $key=>$value):
                        if(
strpos($value, '-')):
                            
$value = str_replace("-", " ", $value);
                            
$value = ucwords(strtolower($value));
                            
$value = str_replace(" ", "-", $value);
                        else:
                           
$value = ucwords(strtolower($value));
                        endif;
                       
$converted_str .= " ".$value;
                    endforeach;
                   return
$converted_str;
            }
?>

Thanks.
And Proud to be a PHP Programmer always :-)

In response to joshuamallory at yahoo dot com:

Using CSS to fix a PHP fault is not the ideal way to solve a problem. CSS is browser dependent and can only be used when the data is presented in a web page. A better fix would be something like this:

<?php
function better_ucwords($string) {
  
$string = ucwords($string);
  
$string = preg_replace('#[\\/][a-z]#e', "strtoupper('$0')", $string);
   return
$string;
}
?>

I did the same thing as Catalin, but for French names.

Here's what I'm doing :

For each word (not considering the single-quote as a word boundary character) :
- Put the word in lower case
- If the word is "de", return, else, put the first letter in upper-case
- See if the second character of the word is a single-quote
- Yes ? Put the next char in upper case
- And if the char before the single quote is D, put it back to lower case (-> d)

This complies with the French rules for capitalization in names.

Sample results :
-d'Afoo Bar
-de Foo Bar
-O'Foo Bar
-Foo'bar

<?php
function my_ucwords($s) {
       
$s = preg_replace_callback("/(\b[\w|']+\b)/s", fixcase_callback, $s);
       
        return
$s;        
       
    }
   
    function
fixcase_callback($word) {

       
$word = $word[1];
       
       
$word = strtolower($word);
       
        if(
$word == "de")
            return
$word;
       
       
$word = ucfirst($word);
       
        if(
substr($word,1,1) == "'") {
            if(
substr($word,0,1) == "D") {
               
$word = strtolower($word);
            }
           
$next = substr($word,2,1);
           
$next = strtoupper($next);
           
$word = substr_replace($word, $next, 2, 1);
        }
       
        return
$word;
    }
?>

ucwords() only excepts whitespace in front of a word, although some chars like '"' or '(' normally have no space between them and the following word:
<?php
$title
= 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo
ucwords(strtolower($title));
?>
prints: Elvis "the King" Presley - (let Me Be Your) Teddy Bear

To avoid this i use a small function adding and deleting blanks behind these chars, and using ucwords() in between:

<?php
function my_ucwords($string)
  {
   
$noletters='"([/'; //add more if u need to
   
for($i=0; $i<strlen($noletters); $i++)
     
$string = str_replace($noletters[$i], $noletters[$i].' ', $string);
   
$string=ucwords($string);
    for(
$i=0; $i<strlen($noletters); $i++)
     
$string = str_replace($noletters[$i].' ', $noletters[$i], $string);
    return
$string;
  }

$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo
my_ucwords(strtolower($title));
?>

prints: Elvis "The King" Presley - (Let Me Be Your) Teddy Bear

A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
   
$tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return
mb_convert_case(
       
str_replace("i", "İ", $tmp[0]), MB_CASE_TITLE, "UTF-8").
       
$tmp[1];
}

function
ucwords_turkish($str) {
    return
preg_replace("/(\\w+)/ue", "ucfirst_turkish('\\\\1').'$2'", $str);
}

$str = "iyilik güzelLİK şeker ";
echo
ucwords($str) ."\\n";   // Iyilik GüzelLİK şeker
echo ucwords_turkish($str); // İyilik GüzelLİK Şeker
?>

Thanks a lot brother.

I tested it with a few variations. It works perfectly. Its really great and simple usage of the existing functions. It would be glad to all PHP folks and good to PHP if these kind of functions will be in PHP library on upcoming releases.

<?php

$name1
= "mark-yves robert";
$name2 = "mark-yves robert-bryan";

echo
'<br/>Name 1 (mark-yves robert) =>'.
ucwordspecific($name1,'-'); //returns Mark-Yves Robert

echo '<br/>Name 2 (mark-yves robert-bryan)

=>'
.ucwordspecific($name2,'-');
//returns Mark-Yves Robert-Bryan

function ucwordspecific($str,$delimiter){
$delimiter_space = '- ';
return
str_replace($delimiter_space,$delimiter,ucwords

(str_replace($delimiter,$delimiter_space,$str)));
}

?>

Proud to be a PHP enthusiast always :-)

ucwords for human names in Brazil.
ucwords personalizada para nomes próprios brasileiros.

<?php
   
/**
     * ucwords for human names in Brazil
     * Edit from http://php.net/manual/pt_BR/function.ucwords.php#112795
     * @param string $str
     * @param array $delimiters
     * @param array $exceptions Exceptions are words you don't want converted
     * @return string
     */
   
function name($str, $delimiters = array(
       
" ",
       
"-",
       
".",
       
"'",
       
"O'",
       
"Mc",
    ),
$exceptions = array(
       
"de",
       
"do",
       
"da",
       
"dos",
       
"das",
    )) {
       
$result = '';

        foreach (
$delimiters as $delimiter) {
           
# If string has a delimiter
           
if (strstr($str, $delimiter)) {

               
$ucfirst = array();
               
# Apply ucfirst to every word
               
foreach (explode($delimiter, mb_strtolower($str)) as $word) {
                   
$word = mb_convert_case($word, MB_CASE_TITLE);

                   
# Working with exceptions
                   
if (in_array(mb_strtoupper($word), $exceptions)) {
                       
$word = mb_strtoupper($word);
                    } elseif (
in_array(mb_strtolower($word), $exceptions)) {
                       
$word = mb_strtolower($word);
                    } elseif (
preg_match('/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/', mb_strtoupper($word))) {
                       
# Is roman numerals? # http://stackoverflow.com/a/267405/437459
                       
$word = mb_strtoupper($word);
                    }

                   
$ucfirst[] = $word;
                }

               
# string's first character uppercased
               
$result = implode($delimiter, $ucfirst);
            }
        }

        return
$result;
    }
?>

This will correct capitalisation in names taking note of special capitalisation for Mc..., Mac..., and O'... Other special cases, of which I am not aware, can be added easily.

This is just a slight improvement on "deepdene at email dot com"'s name_case function... Thank you for original function.

<?php

function name_case($name) {
    if( !
$name ) return $name;
   
$newname = strtoupper($name[0]);
   
$break = false;
    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 ) {
        if(
$break ) {
         
$newname .= strtoupper($subed);
        }
        elseif(
$i > 1 && in_array(substr($newname, $i-2, 2), array('Mc', 'O\'')) || $i > 2 && in_array(substr($newname, $i-3, 3), array('Mac')) ) {
         
$newname .= strtoupper($subed);
        }
        else {
         
$newname .= strtolower($subed);
        }
       
$break = false;
      }
      else {
       
// not a letter - a boundary
       
$newname .= $subed;
       
$break = true;
      }
    }  
    return
$newname;

?>

Convert string to in camel-case, useful for class name patterns:
<?php
/**
   * Convert string to in camel-case, useful for class name patterns.
   *
   * @param $string
   *   Target string.
   *
   * @return string
   *   Camel-case string.
   */
function toCamelCase($string){
   
$string = str_replace('-', ' ', $string);
   
$string = str_replace('_', ' ', $string);
   
$string = ucwords(strtolower($string));
   
$string = str_replace(' ', '', $string);
    return
$string;
}
?>

Example:
toCamelCase(make_mE camel-case pLEase) will return:
MakeMeCamelCasePlease

When attempting to adopt a solution similar to Catalin's post (20-Oct-2008 10:14), I ran into some additional problems. Just a heads up, Catalin's wasn't capitalizing correctly when a name like "O'reilley" appeared at the start of the string or a new line. Also, it doesn't account for locale-sensitivity.

I also needed to recognize additional Irish surnames, such as "McArthur/MacArthur" or "FitzGerald". I also didn't want to misinterpret French as an Irish surname, so, "S'il vous plaît" shouldn't result in the "i" in "S'il" capitalized.

I modified Catalin's version, but it's still not perfect. This version happened to suit my needs, so be sure to assess your own needs before using.

<?php

function my_ucwords($str)
{
   
$str = ucwords($str);

   
// Not perfect
   
return preg_replace(
       
'/
            (?: ^ | \\b )         # assertion: beginning of string or a word boundary
            ( O\' | Ma?c | Fitz)  # attempt to match Irish surnames
            ( [^\W\d_] )          # match next char; we exclude digits and _ from \w
        /xe'
,
       
"'\$1' . strtoupper('\$2')",
       
$str);
}

?>

Here is a function to capitalize a last name, accounting for hyphens, apostrophes, "Mc" and "Mac":

<?php
function CapitalizeLastName($name) {
   
$name = strtolower($name);
   
$name = join("'", array_map('ucwords', explode("'", $name)));
   
$name = join("-", array_map('ucwords', explode("-", $name)));
   
$name = join("Mac", array_map('ucwords', explode("Mac", $name)));
   
$name = join("Mc", array_map('ucwords', explode("Mc", $name)));
    return
$name;
}
?>

I speed tested it against functions that used preg_replace() with an "e" modifier, preg_replace_callback(), and a character-by-character parsing.  Unexpectedly, this function using join(), array_map() and explode() was fastest.

Make the first letter of any word in capital even they are separated by hyphen.

Eg : donzé pierre-yves      => Donzé Pierre-Yves
        joye-cagnard frédéric => Joye-Cagnard Frédéric

<?php

$str
= "donzé pierre-yves";
echo
ucwordsHyphen($str); /*returns Donzé Pierre-Yves*/

function ucwordsHyphen($str){
    return
str_replace('- ','-',ucwords(str_replace('-','- ',$str)));
}
?>

Thanks.

Because I needed a function that did the same as the function proper in Excel I created this little function :

<?php
function proper($string){
 
   
$string = strtolower($string);
   
   
$lettersAndNumbers = 'abcdefghijklmnopqrstuvwxyz01234565789';
   
   
$string[0] = strtoupper($string[0]);
   
    for (
$index = 1;$index < strlen($string);$index++){
      if (
strpos($lettersAndNumbers, $string[$index]) === false){
        if (
$index +1 < strlen($string)){
         
$string[$index+1] = strtoupper($string[$index+1]);
         
$index++;
        }
      }
    }
 
    return(
$string);
   
  }
?>