Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Created March 18, 2020 23:39
Show Gist options
  • Save leocavalcante/268a224cfd8eab471c646fcf51ee8fd7 to your computer and use it in GitHub Desktop.
Save leocavalcante/268a224cfd8eab471c646fcf51ee8fd7 to your computer and use it in GitHub Desktop.
Title case
<?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