Title case a string containing one or more last names while handling names with apostrophes

I want to standardize a user-supplied string. I'd like the first letter to be capitalized for the name and if they have entered two last names, then capitalize the first and second names. For example, if someone enters:

marriedname maidenname

It would convert this to Marriedname Maidenname and so on if there is more than two names.

The other scenario is when someone has an apostrophe in their name. If someone enters:

o'connell

This would need to convert to O'Connell.

I was using:

ucfirst(strtolower($last_name));

However, as you can tell that wouldn't work for all the scenarios.


This will capitalize all word's first letters, and letters immediately after an apostrophe. It will make all other letters lowercase. It should work for you:

str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($last_name))));

you can try this for word's

<?php echo ucwords(strtolower('Dhaka, JAMALPUR, sarishabari')) ?>

result is: Dhaka, Jamalpur, Sarishabari


None of these are UTF8 friendly, so here's one that works flawlessly (so far)

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI"))
{
    /*
     * Exceptions in lower case are words you don't want converted
     * Exceptions all in upper case are any words you don't want converted to title case
     *   but should be converted to upper case, e.g.:
     *   king henry viii or king henry Viii should be King Henry VIII
     */
    $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
    foreach ($delimiters as $dlnr => $delimiter) {
        $words = explode($delimiter, $string);
        $newwords = array();
        foreach ($words as $wordnr => $word) {
            if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                // check exceptions list for any words that should be in upper case
                $word = mb_strtoupper($word, "UTF-8");
            } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                // check exceptions list for any words that should be in upper case
                $word = mb_strtolower($word, "UTF-8");
            } elseif (!in_array($word, $exceptions)) {
                // convert to uppercase (non-utf8 only)
                $word = ucfirst($word);
            }
            array_push($newwords, $word);
        }
        $string = join($delimiter, $newwords);
   }//foreach
   return $string;
}

Usage:

$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos'