Skip to content

Instantly share code, notes, and snippets.

@ahmednuaman
Created October 19, 2011 09:57
Show Gist options
  • Save ahmednuaman/1297873 to your computer and use it in GitHub Desktop.
Save ahmednuaman/1297873 to your computer and use it in GitHub Desktop.
Convert strings to title case
function title_case($string, $delimiters = array(" ", "-", "O'"), $exceptions = array("to", "a", "the", "of", "by", "and", "with", 'it', 'as', "for")) {
/*
* 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
*/
foreach ($delimiters as $delimiter){
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $word){
if (in_array(strtoupper($word), $exceptions)){
// check exceptions list for any words that should be in upper case
$word = strtoupper($word);
} elseif (!in_array($word, $exceptions)){
// convert to uppercase
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment