Skip to content

Instantly share code, notes, and snippets.

@aimfireready
Last active July 26, 2019 02:10
Show Gist options
  • Select an option

  • Save aimfireready/f64dfc809e7dab3e38126b74209411ea to your computer and use it in GitHub Desktop.

Select an option

Save aimfireready/f64dfc809e7dab3e38126b74209411ea to your computer and use it in GitHub Desktop.
<?php
/*
* Capitalize Input String to Title Case
* Saved from on https://stackoverflow.com/a/44748446/4902224
* "Converting String to Title Case - PHP" 2017-06-25
*/
function makeTitleCase($input) {
$smallwordsarray = array('of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','to','into','with','it', 'as' );
//Split input string into an array of words
$words = explode(' ', $input);
foreach ($words as $key => $word) {
// If this word is the first or it's not a "small word", capitalise it.
if ($key == 0 or !in_array(strip_tags($word), $smallwordsarray)) {
$old = strip_tags($word);
$new = ucfirst($old);
$words[$key] = str_replace($old,$new,$word);
}
}
//Put the array of words back into a string
$capitalizedItemName = implode(' ', $words);
return $capitalizedItemName;
}
$title = ['lord of the rings', 'of mice and men', 'in the way', 'mother of pearl', 'wind in the willows', 'organic bananas', 'cream of wheat'];
foreach ($titles as $title) {
echo makeTitleCase($title) . "\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment