Skip to content

Instantly share code, notes, and snippets.

@kirkaracha
Created April 23, 2018 20:34
Show Gist options
  • Save kirkaracha/2620b918d0fd9449fd170e3cdfec23b3 to your computer and use it in GitHub Desktop.
Save kirkaracha/2620b918d0fd9449fd170e3cdfec23b3 to your computer and use it in GitHub Desktop.
Converts string to title case
<?php declare(strict_types=1);
if (!function_exists('titleCase')) {
function titleCase($title)
{
$smallWords = [
'a',
'an',
'and',
'at',
'but',
'by',
'else',
'for',
'from',
'if',
'in',
'into',
'is',
'nor',
'of',
'off',
'on',
'or',
'out',
'over',
'the',
'then',
'to',
'when',
'with'
];
$specialWords = [
'I',
'II',
'III',
'IV',
'V',
'VI',
'VII',
'UK',
'US'
];
$punctuation = [
'.',
'-',
':',
'!',
'?'
];
$words = explode(' ', $title);
foreach ($words as $index => $word) {
$lastCharacterPreviousWord = substr($index -1, -1);
if (
!in_array($word, $smallWords) ||
!in_array($word, $specialWords) ||
in_array($lastCharacterPreviousWord, $punctuation) ||
$index === 0
) {
$words[$index] = ucfirst($word);
}
}
$title = implode(' ', $words);
return $title;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment