Created
March 18, 2020 23:39
-
-
Save leocavalcante/268a224cfd8eab471c646fcf51ee8fd7 to your computer and use it in GitHub Desktop.
Title case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function strtotitle(string $str): string { | |
$title = mb_convert_case($str, MB_CASE_TITLE); | |
// Edge cases | |
return preg_replace_callback_array([ | |
"/('[a-z])/" => fn ($m) => strtoupper($m[1]), | |
"/(\s(?:D(o|a)s?)\s)/" => fn ($m) => strtolower($m[1]), | |
], $title); | |
} | |
// TESTS | |
$tests = [ | |
["Carlo D'ippoliti", "Carlo D'Ippoliti"], | |
["Kerényi ádám", "Kerényi Ádám"], | |
["Matteo Dell'aqcua", "Matteo Dell'Aqcua"], | |
["john o'grady-smith", "John O'Grady-Smith"], | |
["JOHN O'GRADY-SMITH2", "John O'Grady-Smith2"], | |
["john o'grady-smith5", "John O'Grady-Smith5"], | |
["joão da silva", "João da Silva"], | |
["maria das dores", "Maria das Dores"], | |
]; | |
foreach ($tests as [$test, $expected]) { | |
$actual = strtotitle($test); | |
assert($actual === $expected, "Failed `{$test}` got `{$actual}` expecting `{$expected}`"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment