-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapitalizeName.php
71 lines (48 loc) · 2.39 KB
/
capitalizeName.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/**
* Capitalize Name Method
* @author Jabari J. Hunt
*
* Originally created by Armand Niculescu (https://www.media-division.com/correct-name-capitalization-in-php/).
* I reformatted it and added validation to the passed variable.
*
* @param string $name
* @throws Exception Improper input: String expected.
* @return string
*/
private function capitalizeName(string $name): string {
// VALIDATE PASSED STRING
if (!empty($name)) {
// SET INITIAL VARIABLES
$name = str_replace('’', "'", strtolower($name));
$wordSplitters = [' ', '-', "O'", "L'", "D'", 'St.', 'Mc'];
$lowercaseExceptions = ['the', 'van', 'den', 'von', 'und', 'der', 'de', 'da', 'of', 'and', "l'", "d'"];
$uppercaseExceptions = ['III', 'IV', 'VI', 'VII', 'VIII', 'IX'];
// LOOP THROUGH WORD SPLITTERS
foreach ($wordSplitters as $delimiter) {
// SET INITIAL LOOP VARIABLES
$words = explode($delimiter, $name);
$newWords = [];
// LOOP THROUGH WORDS AND DECIDE CASE | DECIDE CASE OF WORD SPLITTER / DELIMITER
foreach ($words as $word) {
if (in_array(strtoupper($word), $uppercaseExceptions)) {
$word = strtoupper($word);
} else if (!in_array($word, $lowercaseExceptions)) {
$word = ucfirst($word);
}
$newWords[] = $word;
}
if (in_array(strtolower($delimiter), $lowercaseExceptions)) {
$delimiter = strtolower($delimiter);
}
// REBUILD NAME
$name = implode($delimiter, $newWords);
}
}
else {
throw new Exception('Improper input: String expected.');
}
// RETURN STRING
return $name;
}
?>