Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uppercase surname, excluding the lowercase prefix section of a surname

Tags:

php

utf-8

I am trying to determine a method to uppercase a surname; however, excluding the lowercase prefix.

Example of names and their conversion:

  • MacArthur -> MacARTHUR
  • McDavid -> McDAVID
  • LeBlanc -> LeBLANC
  • McIntyre -> McINTYRE
  • de Wit -> de WIT

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:

  • Macmaster -> MACMASTER
  • Macintosh -> MACINTOSH

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.

like image 334
JimmyBanks Avatar asked Jan 20 '17 15:01

JimmyBanks


1 Answers

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)
like image 62
deceze Avatar answered Sep 22 '22 20:09

deceze