note 95484 deleted from function.mb-convert-case by danbrown
| From: | danbrown@php.net | Date: | Tue, 05 Jan 2010 16:40:13 +0000 |
| Subject: | note 95484 deleted from function.mb-convert-case by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164662@lists.php.net to get a copy of this message | ||
Note Submitter: viceamarian at gmail dot com
----
A better variant of <b>agash at freemail dot hu</b>'s titleCase function.
Works better when you have multiple types of delimiters in a string (eg.: MY STREET I-VIII).
function titleCase($string, $exceptions_lower = array("de", "pe",
"cu", "la", "si", "nr"), $exceptions_upper =
array("I", "II", "III", "IV", "V", "VI",
"VII", "VIII", "IX", "X")) {
/*
* 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
*/
// Remove white spaces from the begining and from the end of text
$string = trim($string);
// First a simple conversion
$string = strtolower($string);
$string = ucwords($string);
// Find words only
preg_match_all("/[a-zA-Z0-9]+/", $string, $match);
$words = $match[0];
foreach ($words as $ii=>$vv){
if (in_array(strtolower($vv), $exceptions_lower)){
// Check exceptions list for any words that should be in lower case
$new_word = strtolower($vv);
}
elseif (in_array(strtoupper($vv), $exceptions_upper)){
// Check exceptions list for any words that should be in upper case
$new_word = strtoupper($vv);
}
else {
// Convert to uppercase
$new_word = ucfirst($vv);
}
$string = str_replace($vv, $new_word, $string);
}
return $string;
}