Given upper case names transform to Proper Case, handling "O'Hara", "McDonald" "van der Sloot" etc

php, regex, text, text-parsing, text-processing

Solution

Using regular expressions in a short provided list could be easy, but if you must handle hundreds or thousands of records it's very hard to be bullet proof.

I'd rather use something that can't affect someone else. How do you know if Mr. "MACDONALD" prefers "Macdonald"?

You're correcting someone else's error. If source cannot be corrected you could use something like this:

<?php

$provided_names = array(
  "SMITH",
  "O'HARA",
  "MCDONALD",
  "JONES",
  "VAN DER SLOOT",
  "MACDONALD"
);

$corrected_names = array(
  "O'HARA"        => "O'Hara",
  "MCDONALD"      => "McDonald",
  "VAN DER SLOOT" => "van der Sloot"
);

$email_text = array();

foreach ($provided_names as $provided_name)
{
  $provided_name = !array_key_exists($provided_name, $corrected_names) 
    ? ucwords(strtolower($provided_name)) 
    : $corrected_names[$provided_name];
  $email_text[]  = "{$provided_name}, your message text.";
}

print_r($email_text);

/* output:
Array
(
  [0] => Smith, your message text.
  [1] => O'Hara, your message text.
  [2] => McDonald, your message text.
  [3] => Jones, your message text.
  [4] => van der Sloot, your message text.
  [5] => Macdonald, your message text.
)
*/
?>

I hope it be useful.

Problem

I am provided a list of names in upper case. For the purpose of a salutation in an email I would like them them to be Proper Cased. Easy enough to do using PHP's ucwords. But I feel I need some regex function to handle common exceptions, such as: "O'Hara", "McDonald", "van der Sloot", etc It's not so much that I need help constructing a regex statement to handle the three examples above (tho that would be nice), as it is that I don't know what all the common exceptions might be. Surely someone has faced this issue before, any pointers to published solutions or something you could share?

Original source