Skip to content

Instantly share code, notes, and snippets.

@adrianb93
Last active September 1, 2015 10:19
Show Gist options
  • Save adrianb93/ecfd7ab2179c8c420b0d to your computer and use it in GitHub Desktop.
Save adrianb93/ecfd7ab2179c8c420b0d to your computer and use it in GitHub Desktop.
Title capitalisation function. Converts strings to title case.
<?php
// Title capitalisation function
function title_caps($string) {
// Needs work on recognising prepositions
$conjunctions = [ 'an', 'and', 'as', 'at', 'but', 'by', 'else', 'etc', 'for', 'from', 'if', 'in', 'into',
'is', 'nor', 'of', 'off', 'on', 'or', 'per', 'out', 'over', 'so', 'the', 'then', 'to',
'up', 'via', 'vs', 'when', 'with', 'yet' ];
// Uppercase first letter of all words
$string = preg_split('/(\W+)/', strtolower($string), -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($string as $key => $s) $string[$key] = ucwords($s);
$string = implode('', $string); // Result: toys-r-us = Toys-R-Us
// Make all conjunctions and articles lowercase
foreach ($conjunctions as $word) {
$pattern = "/(^|\s|[[:punct:]])" . ucwords($word) . "($|\s|[[:punct:]])/";
for ($i = 0; $i < preg_match_all($pattern, $string); $i++) {
$string = preg_replace_callback(
$pattern,
function($matches) {
return strtolower($matches[0]);
},
$string
);
}
}
// Single character words to lowercase
$pattern = "/(^|\s|[[:punct:]])[A-Z]($|\s|[[:punct:]])/";
for ($i = 0; $i < preg_match_all($pattern, $string); $i++) {
$string = preg_replace_callback(
$pattern,
function($matches) {
return strtolower($matches[0]);
},
$string
);
}
// Capitalise the first and last word
$string = explode(' ', ucfirst($string)); // First word
$string[count($string) - 1] = ucfirst($string[count($string) - 1]); // Last word
return implode(' ', $string);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment