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"