I am trying to determine a method to uppercase a surname; however, excluding the lowercase prefix.
Example of names and their conversion:
There are also names that would contain the surnames that would need to be fully capitalized, so a simple function to identify the prefix such as strchr()
would not suffice:
The PHP function mb_strtoupper()
is not appropriate, as it capitalizes the complete string. Similarly strtoupper()
is not appropriate, and loses accents on accented names as well.
There are some answers around SO that partly answer the question, such as : Capitalization using PHP
However, the common shortfall is assuming that all names with a surname as as Mac
are followed with a capital.
The names are capitalized properly in the database, so we can assume that a name spelled as Macarthur is correct, or MacArthur is correct for another person.
Going with the rule to capitalise everything after the last capital letter:
preg_replace_callback('/\p{Lu}\p{Ll}+$/u',
function ($m) { return mb_strtoupper($m[0]); },
$name)
\p{Lu}
and \p{Ll}
are Unicode upper and lower case characters respectively, and mb_strtoupper
is unicode aware… for a simple ASCII-only variant this would do too:
preg_replace_callback('/[A-Z][a-z]+$/',
function ($m) { return strtoupper($m[0]); },
$name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With