文字

ucwords

(PHP 4, PHP 5)

ucwords将字符串中每个单词的首字母转换为大写

说明

string ucwords ( string $str )

str 中每个单词的首字符(如果首字符是字母)转换为大写字母,并返回这个字符串。

这里单词的定义是紧跟在空白字符(空格符、制表符、换行符、回车符、水平线以及竖线)之后的子字符串。

参数

str

输入字符串。

返回值

返回转换后的字符串。

范例

Example #1 ucwords() 范例

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

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

注释

Note: 此函数可安全用于二进制对象。

参见

  • strtoupper() - 将字符串转化为大写
  • strtolower() - 将字符串转化为小写
  • ucfirst() - 将字符串的首字母转换为大写
  • mb_convert_case() - 对字符串进行大小写转换

用户评论:

[#1] jgestiotgmailcom [2015-11-24 20:25:55]

This function causes an error in PHP 5.6 if you attempt to pass the second optional parameter. Also it requires the string to be in lower case. Might be better to rewrite this function to make it work.

[#2] Lech [2015-09-01 14:36:31]

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$i1);
      if( 
ord($subed) > 64 && ord($subed) < 123 || ord($subed) > 48 && ord($subed) < 58 ) {
        if( 
$break ) {
          
$newname .= strtoupper($subed);
        }
        elseif( 
$i && in_array(substr($newname$i-22), array('Mc''O\'')) || $i && in_array(substr($newname$i-33), array('Mac')) ) {
          
$newname .= strtoupper($subed); 
        }
        else {
          
$newname .= strtolower($subed);
        }
        
$break false;
      }
      else {
        
// not a letter - a boundary
        
$newname .= $subed;
        
$break true;
      }
    }   
    return 
$newname;

?>

[#3] coder22 at nycap dot rr dot com [2015-06-04 16:26:44]

After a while of trial and error it appears that ucwords does not convert a string that is already in all caps to the ucwords format as inidcated in the beginning of the function manual.

for example, 
$a = my text
$b = ucwords($a)
echo $b = My Text.

However:
$a = MY TEXT;
$b = ucwords($a)
echo $b = MY TEXT

if the string is already uppercase, the function will not use strtolower then ucwords which is interpreted up above.  I just wanted people to know that.  I could not figure out what was going on.

[#4] Alex Milkovskyi [2015-05-13 09:22:58]

Convert string to in camel-case, useful for class name patterns:
<?php

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

[#5] Florian [2015-02-20 08:03:09]

to convert first letters in a firstname like: "jean-pierre" to "Jean-Pierre":

I simply replace the '-' with a vertical tabulation, because the ucwords() function replace the letter just after it.

so, I use the sentence:
$result=str_replace(chr(11),'-',ucwords(strtolower(str_replace('-',chr(11),$firstname))));

[#6] OneOfOne [2013-10-18 20:46:04]

This function will work on anything, not just words separated by spaces. (eg: 'ac/bc/dc,xc zz' => 'Ac/Bc/Dc,Xc Zz')

function ucwords_all($str) {
return preg_replace_callback('/\b(\w)/', function($m) {
return strtoupper($m[0]);
}, $str);
}

[#7] sunamak at odeva dot com [2013-08-14 00:30:44]

function ucwords_tr($str) {
    return mb_convert_case(str_replace(array('i', 'I'), array('?', '?'), $str), MB_CASE_TITLE, 'UTF-8');
}

[#8] antoniomax at antoniomax dot com [2013-07-23 18:04:40]

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"))
    {
        

        
$string mb_convert_case($stringMB_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' 
?>

[#9] ATOLYE15 [2013-06-06 09:11:38]

This solution is a proper use of capitalize first letters of "TURKISH" sentence by AT?LYE15 crew.

function ucwordstr($sentence)
{
        $letters = array('I','?','?','?','?','?','?');
        $replace = array('?','i','?','?','??','?','?');

        $sentence = mb_strtolower(str_replace($letters,$replace,$sentence),"UTF-8");

        $words = array();

        foreach(explode(" ",$sentence) as $word)
        {
            $first = str_replace($replace,$letters,mb_substr($word, 0, 1, "UTF-8"));
            $other = mb_substr($word,1,strlen($word)-1,"UTF-8");

            $words[] = $first.$other;
        }

        $sentence = implode(" ",$words);

        return ucwords($sentence);
}

[#10] hrvoj3e at gmail dot com [2013-04-30 14:44:20]

UTF-8 Title Case that works for me even with hyphens involved!

$str = '?aa?aa-AAAaaa, BBbb';

$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

echo($str): '?aa?aa-Aaaaaa, Bbbb'

[#11] Luca Borrione luca -a email -d c_o_m [2012-09-10 15:41:45]

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_splitstr_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($word01$encoding), $encoding).mb_substr($word1mb_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_specificmb_strtolower($string'UTF-8'), "-'");
?>


Output:
Jean-Paul D'Artagnan ??-???-??? Hello - World

[#12] qeremy [atta] gmail [dotta] com [2012-02-27 17:09:04]

A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    
$tmp preg_split("//u"$str2PREG_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 
?>

[#13] haijerome at gmail dot com [2011-11-21 09:14:23]

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

[#14] Anonymous [2011-11-20 11:06:06]

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

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


 Thanks.

[#15] haijerome at gmail dot com [2011-11-11 23:38:31]

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

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

[#16] ahmet363 at gmail dot com [2011-10-16 11:14:51]

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

[#17] Philippe [2011-09-30 05:54:53]

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 +strlen($string)){
          
$string[$index+1] = strtoupper($string[$index+1]);
          
$index++;
        }
      }
    }
  
    return(
$string);
    
  }
?>

[#18] gabe at fijiwebdesign dot com [2011-08-24 11:49:15]

Another ucwords function with custom separator. 

<?php
function ucwords_custom($str$sep)
{
    return 
preg_replace_callback('/' preg_quote($sep) . './i'create_function(
        
'$match',
        
'return strtoupper($match[0][1]);'
    
), $str);
}
?>


or simpler with PHP5.3

<?php
function ucwords_custom2($str$sep ' ')
{
    return 
preg_replace_callback('/' preg_quote($sep) . './i', function($match) {
        return 
strtoupper($match[0][1]);
    }, 
$str);
}
?>

[#19] Sebstian Espinosa [2011-08-04 16:16:26]

Is more simple to use str_replace to use ucwords without using space as separator like:

<?php

function ucwordsEx($str$separator){

      
$str str_replace($separator" "$str);
      
$str ucwords(strtolower($str));
      
$str str_replace(" "$separator$str);
      return 
$str;

}

echo ucwordsEx("HELLO-my-NAME-iS-maNolO""-");


?>

[#20] jmarois at ca dot ibm dot com [2010-02-12 08:51:46]

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($delimiterarray_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:

?>


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

[#21] Kovik [2009-12-27 07:37:41]

ucwords() only uses whitespace as a delimiter. I found that I needed the ability to use other delimiters for denoting words.

Example: Transforming "content-type" into "Content-Type".

<?php

function capitalizeWords($words$charList null) {
    
// Use ucwords if no delimiters are given
    
if (!isset($charList)) {
        return 
ucwords($words);
    }
    
    
// Go through all characters
    
$capitalizeNext true;
    
    for (
$i 0$max strlen($words); $i $max$i++) {
        if (
strpos($charList$words[$i]) !== false) {
            
$capitalizeNext true;
        } else if (
$capitalizeNext) {
            
$capitalizeNext false;
            
$words[$i] = strtoupper($words[$i]);
        }
    }
    
    return 
$words;
}
?>


Testing:
<?php
echo capitalizeWords('this is a test');  // This Is A Test
echo capitalizeWords('this-is-a-test');  // This-is-a-test
echo capitalizeWords('this is a test'' ');  // This Is A Test
echo capitalizeWords('this-is-a-test''-');  // This-Is-A-Test
echo capitalizeWords('this-is a-test'' ');  // This-is A-test
echo capitalizeWords('this-is a-test''-');  // This-Is a-Test
echo capitalizeWords('this-is a-test'' -');  // This-Is A-Test
?>

[#22] robert at broofa dot com [2009-07-08 06:42:33]

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

[#23] Greg S [2009-04-26 09:16:30]

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$next21);
        }
        
        return 
$word;
    }
?>

[#24] vista_ at live dot se [2008-11-17 02:02:54]

<?php
      
if(!function_exists('mb_ucwords'))
      {
            function 
mb_ucwords($str)
            {
                  return 
mb_convert_case($strMB_CASE_TITLE"UTF-8");
            }
      }
?>

[#25] dyer85 at gmail dot com [2008-11-07 03:33:16]

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);
}

?>

[#26] strazds at gmail dot com [2008-11-01 02:45:15]

ucwords for UTF-8 strings:

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

[#27] Catalin [2008-10-20 07:14:41]

I have looked for a work-around that would upper-case letter after an ' too. 

For example, 

ucword("o'lunney's");

would output "O'lunney's" and I wanted it to output "O'Lunney's".

Here is my function:

<?php
function my_ucwords($string) {
        
$string ucwords(strtolower($string));
        
$string preg_replace_callback("/( [ a-zA-Z]{1}')([a-zA-Z0-9]{1})/s",create_function('$matches','return $matches[1].strtoupper($matches[2]);'),$string);
        return 
$string;
}
?>


Hope it helps someone.

[#28] Alex [2008-08-27 09:43:26]

A modified sentenceNormalizer by gregomm
 
Features:
1- Removes duplicated question marks, exclamations and periods
2- Capitalize first letter of a sentence.
3- Split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the end of each sentence
5- Retains newlines

--removed from orginal function--
undestand the meaning of "?" and "?" in languages like spanish.
undestand the htmlentitity version of this simbols.
--removed from orginal function--

<?php
function sentenceNormalizer($sentence_split) {
    
$sentence_split preg_replace(array('/[!]+/','/[?]+/','/[.]+/'),
                                   array(
'!','?','.'),$sentence_split);        
    
    
$textbad preg_split("/(\!|\.|\?|\n)/"$sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
    
$newtext = array();
    
$count sizeof($textbad);
    
    foreach(
$textbad as $key => $string) {
        if (!empty(
$string)) {
            
$text trim($string' ');
            
$size strlen($text);
            
            if (
$size 1){     
                
$newtext[] = ucfirst(strtolower($text));
            }
                elseif (
$size == 1) {
                    
$newtext[] = ($text == "\n") ? $text $text ' ';
                }      
        }
    }
    
    return 
implode($newtext);
}
?>

[#29] majd87 at gmail dot com [2008-08-05 18:58:25]

I modified Q1712's code (below) to use regular expressions 
instead of characters to properly capitalize words that fall 
directly after an unwanted character. See his post for details.

This version allows me to use it around html elements, etc.

<?php
    
function my_ucwords($string){ 

        
$invalid_characters = array('"',
                                    
'\(',
                                    
'\[',
                                    
'\/',
                                    
'<.*?>',
                                    
'<\/.*?>');

        foreach(
$invalid_characters as $regex){
            
$string preg_replace('/('.$regex.')/','$1 ',$string);
        }

        
$string=ucwords($string);

        foreach(
$invalid_characters as $regex){
            
$string preg_replace('/('.$regex.') /','$1',$string);
        }

        return 
$string;
    }
?>


Moreover, to get a proper title case, i combine it with this function:

This Function is obtained from: 
http://codesnippets.joyent.com/posts/show/716

<?php
    
function title_case($title) {
        
$smallwordsarray = array(
            
'of','a','the','and','an','or','nor','but','is','if','then',
'else','when',
            
'at','from','by','on','off','for','in','out',
'over','to','into','with'
        
);

        
$words explode(' '$title);
        foreach (
$words as $key => $word)
        {
            if (
$key == or !in_array($word$smallwordsarray))
            
$words[$key] = $this->my_ucwords(strtolower($word));
        }

        
$newtitle implode(' '$words);
        return 
$newtitle;
    }
?>

Hope you find it useful.

[#30] gregomm at gmail dot com [2008-05-23 00:38:21]

An improved of ucsentence. In fact its a function to avoid ugly data entry. It's based on code taken from this page. Can be inproved for better performance, of course...

Features:
1- removes duplicated question marks, an exclamations
2- Capitalize first letter of a sentence.
3- split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the begining of each sentence
5- undestand the meaning of "?" and "?" in languages like spanish.
6- undestand the htmlentitity version of this simbols.

function sentenceNormalizer( $sentence_split ) {

    $sentence_split = preg_replace("/[!]+/","!",$sentence_split);
    $sentence_split = preg_replace("/[?]+/","?",$sentence_split);
    $sentence_split = preg_replace("/[?]+/","?",$sentence_split);
    $sentence_split = preg_replace("/[?]+/","?",$sentence_split);     
         
$textbad = preg_split("/(\<[a-zA-Z0-9-]*\>".
"\!(\s)?|\.(\s)?|\?(\s)?|?(\s)?|?(\s)?".
"|&iquest;(\s)?|&iexcl;(\s)?)/",
         $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE); 
    $newtext = array();
    $count = sizeof($textbad);
    
    $prevStr ="";
    
    for ($i = 0; $i < $count; $i++){
    
$text = trim($textbad[$i]);
$size = strlen($text);

     if ($size>1){    

     $sentencegood=ucfirst(strtolower($text));               
    
     if ($i>0 && $prevStr != '?' && $prevStr != '?' && $prevStr !="&iquest;" && $prevStr !="&iexcl;"){
     $sentencegood =" ".$sentencegood;
     }
        $newtext[] = $sentencegood;
        $prevStr =$text;
        
     }elseif($size==1 ){
    
     if ($i>0 && ($text == '?' || $text == '?' || $prevStr =="&iquest;" || $prevStr =="&iexcl;") ){
     $newtext[] =" ".$text;     
     }else{
     $newtext[] =$text;
     }
     $prevStr =$text;
     }
    
    }

    $textgood = implode($newtext);
    return $textgood;
}

[#31] NoName [2008-03-12 12:03:35]

For strings with diactrical marks (umlauts, etc.), consider mb_convert_case.

[#32] blake at goinoutwest dot com [2008-01-29 17:14:27]

Relating to the mb_ucwords() function posted by Anonymous.  In order for this to actually be multi-byte compliant, you would also need to use mb_substr() and mb_strlen() instead of substr and strlen respectively.

Here it is corrected and extended even further to allow multiple word separators and a list of exceptions to correct after title casing. It's a bit tedious and inelegant, but things frequently are when dealing with human languages.

function mb_ucwords($str) {
$exceptions = array();
$exceptions['Hp'] = 'HP';
$exceptions['Ibm'] = 'IBM';
$exceptions['Gb'] = 'GB';
$exceptions['Mb'] = 'MB';
$exceptions['Cd'] = 'CD';
$exceptions['Dvd'] = 'DVD';
$exceptions['Usb'] = 'USB';
$exceptions['Mm'] = 'mm';
$exceptions['Cm'] = 'cm';
// etc.

$separator = array(" ","-","+");

    $str = mb_strtolower(trim($str));
foreach($separator as $s){
    $word = explode($s, $str);

    $return = "";
    foreach ($word as $val){
        $return .= $s . mb_strtoupper($val{0}) . mb_substr($val,1,mb_strlen($val)-1);
    }
$str = mb_substr($return, 1);
}

foreach($exceptions as $find=>$replace){
if (mb_strpos($return, $find) !== false){
$return = str_replace($find, $replace, $return);
}
}
    return mb_substr($return, 1);
}

[#33] Anonymous [2007-12-16 03:09:42]

Function to do what ucwords is intended to do - just correctly also for international char sets:

function mb_ucwords($s)
{
    $s = mb_strtolower(trim($s));
    $w = explode(" ", $s);
    
    $return = "";
    foreach ($w as $val)
    {
        $return .= " " . mb_strtoupper($val{0}) . substr($val,1,strlen($val)-1);
    }
    return trim($return);
}

Building on an earlier snippet here.

[#34] kendsnyder at gmail dot com [2007-07-30 13:02:39]

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.

[#35] Q1712 at online dot ms [2007-05-05 00:49:23]

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

[#36] barnaby ritchley at exeye dot co dot uk [2007-01-03 08:53:26]

A very easy way to convert to title case:

function titleCase($string)
     {
     return ucwords(strtolower($string));
     }

$myString = "SOME TEXT";

echo titleCase($myString);

//will print, "My Text"

[#37] max at phoenixweb dot it [2006-09-15 07:35:40]

I have rewritten a UCSMART function adding a feature to translate special ASCII char (windows occidental ascii charset):

You can edit/add/delete char by use the first two string (be carefull to preserve the order of the string).

Enjoy!

<?php
$ASCII_SPC_MIN 
"???????????????????????????????????????????";
$ASCII_SPC_MAX "???????????????????????????????";

function 
str2upper($text) {
    global 
$ASCII_SPC_MIN,$ASCII_SPC_MAX;
    return 
strtr(strtoupper($text),$ASCII_SPC_MIN,$ASCII_SPC_MAX);
}
function 
str2lower($text) {
    global 
$ASCII_SPC_MIN,$ASCII_SPC_MAX;
    return 
strtr(strtolower($text),$ASCII_SPC_MAX,$ASCII_SPC_MIN);
}
function 
ucsmart($text) {
    global 
$ASCII_SPC_MIN;
    return 
preg_replace(
        
'/([^a-z'.$ASCII_SPC_MIN.']|^)([a-z'.$ASCII_SPC_MIN.'])/e',
        
'"$1".str2upper("$2")',
        
str2lower($text)
    );
}
?>


Massimiliano Cuttini

[#38] marco at hotelsandgo dot com [2006-09-09 09:35:21]

ucwords that works also with apices: '
for example: "aquila d'abruzzo" became "Aquila d'Abruzzo"
The second part after the // comment can removed! Is optimized for italian language (leave lowercase articles, prepositions, conjunctions) but easily changeable. Notice che "'s"!! for example "hotel 2000's" becames "Hotel 2000's".

function my_ucwords($s)
{
$a=strtolower($s);
$s=ucfirst($a);
for($x=0; $x<strlen($s)-1; $x++)
if(!ctype_alpha($s[$x])) $s[$x+1]=strtoupper($s[$x+1]);

//Lascia minuscoli articoli, preposizioni, congiunzioni
$minuscole=array("il", "lo", "la", "i", "gli", "le", //ARTICOLI DETERMINATIVI
 "un", "uno", "una", //ARTICOLI INDETERMINATIVI
 "e",  "d", "l", "s", "un", //CONGIUNZIONI e CONTRATTI
 "di", "a", "da", "in", "con", "su", "per", "tra", "fra", //PREPOSIZIONI SEMPLICI
 "del", "dello", "della", "dei", "degli", "delle", //PREPOSIZIONI ARTICOLATE
 "a", "al", "allo", "alla", "ai", "agli", "alle",
 "da", "dal", "dallo", "dalla", "dai", "dagli", "dalle",
 "in", "nel", "nello", "nella", "nei", "negli", "nelle",
 "con", "col", "collo", "colla", "coi", "cogli", "colle",
 "su", "sul", "sullo", "sulla", "sui", "sugli", "sulle",
 "per", "pel", "pei");

foreach($minuscole as $value)
{
$pos=strpos($a, $value);
if( ( $pos>0 && $pos<strlen($s)-1 && !ctype_alpha($a[$pos-1]) && !ctype_alpha($a[$pos+1]) ) //CARATTERE IN MEZZO
||  ( $pos==strlen($s)-1 && !ctype_alpha($a[$pos-1]) ) ) //CASO PARTICOLARE: carattere in fondo. x es: "hotel 2000's"
$s[$pos]=strtolower($s[$pos]);
}

return $s;
}

function my_ucwords_essential($s)
{
$a=strtolower($s);
$s=ucfirst($a);
for($x=0; $x<strlen($s)-1; $x++)
if(!ctype_alpha($s[$x])) $s[$x+1]=strtoupper($s[$x+1]);

return $s;
}

Can be rewritten better, I Know

[#39] philip at fcknet dot dk [2006-08-08 05:11:20]

Before noticing this function I made the following function (that does the same as ucwords):

<?php
function firstUpper($string)
{
    
$string str_replace(array("?","?","?"), array("?","?","?"), strtolower($string));
    
$ord explode(" "$string);
    
    
$return "";
    foreach (
$ord as $val)
    {

        
$return .= " " str_replace(array("?","?","?"), array("?","?","?"), strtoupper($val{0})) . substr($val,1,strlen($val)-1);
    }
    return 
$return;
}
?>


It also converts Danish letters without using the setlocale function.

[#40] starmonkey [at] evolove [dot] net [2006-08-05 08:17:43]

Simple helper function to walk through a nested array of strings and upper case them:

<?php

function _capitalize($input) {
    if(
is_array($input)) {
        
// recurse through array elements (using a reference)
        
foreach($input as &$value) {
            
$value _capitalize($value);
        }
        return 
$input;
    } elseif(
is_string($input)) {
        
// process this string
        
return ucwords($input);
    } else {
        
// all other data types, leave alone
        
return $input;
    }
}
?>

[#41] Ismet Togay [2006-05-30 17:07:57]

Response to arif:

We do not need that long functions. In order to make ucwords() worked properly in Turkish words that contain speacial characters, we can use the following command in our php codes:

setlocale(LC_ALL, 'tr_TR');

This will set locale to Turkish.

[#42] lev at phpfox dot com [2006-05-06 01:44:09]

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!

[#43] [2005-12-24 07:34:36]

"ieure at php dot net", your idea is pure poetry!

The function below will standardize the capitalization on people's names and the titles of reports and essays . You may need to adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function my_ucwords($str, $is_name=false) {
   // exceptions to standard case conversion
   if ($is_name) {
       $all_uppercase = '';
       $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';
   } else {
       // addresses, essay titles ... and anything else
       $all_uppercase = 'Po|Rr|Se|Sw|Ne|Nw';
       $all_lowercase = 'A|And|As|By|In|Of|Or|To';
   }
   $prefixes = 'Mc';
   $suffixes = "'S";

   // captialize all first letters
   $str = preg_replace('/\\b(\\w)/e', 'strtoupper("$1")', strtolower(trim($str)));

   if ($all_uppercase) {
       // capitalize acronymns and initialisms e.g. PHP
       $str = preg_replace("/\\b($all_uppercase)\\b/e", 'strtoupper("$1")', $str);
   }
   if ($all_lowercase) {
       // decapitalize short words e.g. and
       if ($is_name) {
           // all occurences will be changed to lowercase
           $str = preg_replace("/\\b($all_lowercase)\\b/e", 'strtolower("$1")', $str);
       } else {
           // first and last word will not be changed to lower case (i.e. titles)
           $str = preg_replace("/(?<=\\W)($all_lowercase)(?=\\W)/e", 'strtolower("$1")', $str);
       }
   }
   if ($prefixes) {
       // capitalize letter after certain name prefixes e.g 'Mc'
       $str = preg_replace("/\\b($prefixes)(\\w)/e", '"$1".strtoupper("$2")', $str);
   }
   if ($suffixes) {
       // decapitalize certain word suffixes e.g. 's
       $str = preg_replace("/(\\w)($suffixes)\\b/e", '"$1".strtolower("$2")', $str);
   }
   return $str;
}

// A name example
print my_ucwords("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John

// A title example
print my_ucwords("to be or not to be");
// Output: "To Be or Not to Be"

[#44] ieure at php dot net [2005-12-04 14:57:29]

Whoa guys, tone things down a bit here. No need to loop and implode. This is a one-line solution:

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.

[#45] gothicbunny at hotmail dot com [2005-11-08 16:16:48]

Here is a simple, yet winded, opposite to ucwords.

<?php

function lcwords($string)
{
    

    #loop variable
    
$a 0;
    
#store all words in this array to be imploded and returned
    
$string_new = array();
    
#create array of all words
    
$string_exp explode(" ",$string);
    foreach(
$string_exp as $astring)
    {
        for(
$a=0;$a<strlen($astring);$a++)
        {
            
#check that the character we are at {pos $a} is a word
            #i.e. if the word was !A the code would fail at !
            #then loop to the next character and succeed at A
            #check at character position $a
            
if(preg_match("'\w'",$astring[$a]))
            {
                
$astring[$a] = strtolower($astring[$a]);
                
#end the loop
                
break;
            }
        }
        
$string_new[] = $astring;
    }
    
#recreate the string from array components using space deliminator
    
return implode(" ",$string_new);
}
?>


Of course a simplier way would be to use a callback, but I like working with long code :)

[#46] [2005-10-20 16:14:40]

Here's a  piece that allows you to use the contents of a directory..  capitalizes the words and make links.. this particular example splits file names at _ and only selects file with .htm extensions (thought you could use any extension and call it using  include()  or soom such)
ie my_file_name.htm will produce
<a href="my_file_name.htm">My File Name</a>

<?php
$path 
"/home/path/to/your/directory";
   
$mydir dir($path);
   while((
$file $mydir->read()) !== false) {
     if(
substr($file, -4)=='.htm'){
    
$trans = array("_" => " "".htm" => ""); // creates the editing array
    
$newlist strtr($file$trans); // edits using editing array
    
echo "<a href=\"".$file."\">".ucwords($newlist)."</a><br>";
     }
    }
   
?>

[#47] radley25 at nospam dot spamcop dot net [2005-07-04 20:06:17]

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

[#48] igua no-spam at coveruniverse dot com [2005-03-08 04:30:16]

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

[#49] joshuamallory at yahoo dot com [2004-11-14 20:08:39]

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

[#50] babel - nospamplease - sympatico - ca [2004-02-10 20:26:43]

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.

[#51] deepdene at email dot com [2002-12-09 23:20:33]

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

[#52] [2002-01-18 18:14:34]

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]

[#53] Julienc at psychologie-fr dot com [2001-11-03 19:06:12]

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

[#54] neil at no-spam-ents24 dot com [2001-03-21 05:10:07]

The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:

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

上一篇: 下一篇: