ucwords
(PHP 4, PHP 5, PHP 7, PHP 8)
ucwords — 文字列の各単語の最初の文字を大文字にする
説明
文字が "a"
(0x61) から "z"
(0x7a) までのアルファベットの場合、
string
の各単語の最初の文字を大文字にしたものを返します。
この関数における "単語" とは、
separators
に含まれていない文字からなる文字列です。
separators
のデフォルトはスペース、
フォームフィード、改行、キャリッジリターン、
水平タブ、垂直タブ です。
マルチバイト文字列に対して類似の変換を行うには、
mb_convert_case()
を MB_CASE_TITLE
モードで使います。
パラメータ
string
-
入力文字列。
separators
-
オプションの
separators
で、単語の区切り文字を指定します。
戻り値
変更後の文字列を返します。
変更履歴
バージョン | 説明 |
---|---|
8.2.0 | ケース変換は、setlocale() で設定されたロケールに依存しなくなりました。 ASCII 文字のみが変換されます。 |
例
例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!
?>
例2 ucwords() で、区切り文字を指定する例
<?php
$foo = 'hello|world!';
$bar = ucwords($foo); // Hello|world!
$baz = ucwords($foo, "|"); // Hello|World!
?>
例3 ucwords() で、追加の区切り文字を指定する例
<?php
$foo = "mike o'hara";
$bar = ucwords($foo); // Mike O'hara
$baz = ucwords($foo, " \t\r\n\f\v'"); // Mike O'Hara
?>
注意
注意: この関数はバイナリデータに対応しています。
参考
- strtoupper() - 文字列を大文字にする
- strtolower() - 文字列を小文字にする
- ucfirst() - 文字列の最初の文字を大文字にする
- mb_convert_case() - 文字列に対してケースフォールディングを行う
+add a note
User Contributed Notes 28 notes
antoniomax at antoniomax dot com ¶
11 years ago
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'
?>
jmarois at ca dot ibm dot com ¶
14 years ago
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.
NOSPAM dot php at my dot jrklein dot com ¶
4 years ago
Based on code sample originally posted by "Anonymous" on 2005-12-14. The /e modifier is no longer supported by preg_replace(). Rewritten to use preg_replace_callback() instead. Tested with PHP 7.3.
The function below will standardize the capitalization on people's names, addresses, and the titles of reports and essays . Adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.
function ucwords_title($string, $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 = 'Us|Ca|Mx|Po|Rr|Se|Sw|Ne|Nw';
$all_lowercase = 'A|And|As|By|In|Of|Or|To';
}
$prefixes = 'Mac|Mc';
$suffixes = "'S";
// Trim whitespace and convert to lowercase
$str = strtolower(trim($string));
// Capitalize all first letters
$str = preg_replace_callback('/\\b(\\w)/', function ($m) {
return strtoupper($m[1]);
}, $str);
if ($all_uppercase) {
// Capitalize acronyms and initialisms (e.g. PHP)
$str = preg_replace_callback('/\\b(' . $all_uppercase . ')\\b/', function ($m) {
return strtoupper($m[1]);
}, $str);
}
if ($all_lowercase) {
// Decapitalize short words (e.g. and)
if ($is_name) {
// All occurrences will be changed to lowercase
$str = preg_replace_callback('/\\b(' . $all_lowercase . ')\\b/', function ($m) {
return strtolower($m[1]);
}, $str);
} else {
// First and last word will not be changed to lower case (i.e. titles)
$str = preg_replace_callback('/(?<=\\W)(' . $all_lowercase . ')(?=\\W)/', function ($m) {
return strtolower($m[1]);
}, $str);
}
}
if ($prefixes) {
// Capitalize letter after certain name prefixes (e.g 'Mc')
$str = preg_replace_callback('/\\b(' . $prefixes . ')(\\w)/', function ($m) {
return $m[1] . strtoupper($m[2]);
}, $str);
}
if ($suffixes) {
// Decapitalize certain word suffixes (e.g. 's)
$str = preg_replace_callback('/(\\w)(' . $suffixes . ')\\b/', function ($m) {
return $m[1] . strtolower($m[2]);
}, $str);
}
return $str;
}
// A name example
print ucwords_title("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John
// A title example
print ucwords_title("to be or not to be");
// Output: "To Be or Not to Be"
robert at broofa dot com ¶
15 years ago
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
almino dot melo at gmail dot com ¶
8 years ago
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;
}
?>
lev at phpfox dot com ¶
18 years ago
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!
kendsnyder at gmail dot com ¶
17 years ago
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.
blake at goinoutwest dot com ¶
16 years ago
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);
}
ahmet363 at gmail dot com ¶
13 years ago
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
hrvoj3e at gmail dot com ¶
11 years ago
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'
Luca Borrione luca -a email -d c_o_m ¶
12 years ago
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
strazds at gmail dot com ¶
16 years ago
ucwords for UTF-8 strings:
<?php
function mb_ucwords($str) {
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
return ($str);
}
?>
Q1712 at online dot ms ¶
17 years ago
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
Anonymous ¶
22 years ago
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]
Anonymous ¶
18 years ago
"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"
barnaby ritchley at exeye dot co dot uk ¶
17 years ago
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"