phpstringcapitalizetitle-casehumanize

Capitalize last names including exceptions like mccall => McCall


I am having trouble with the capitalization of names using PHP. There are some names that have 2 capital letters in them (ex: McCall). When storing a users name that registers for our website, we run the following code:

$name = ucwords(strtolower(trim($_SESSION['last_name']))) ;

What this does is change 'mccall' to 'Mccall'. What we need is a way to check if the first 2 letters begin with 'Mc' and if so, the 3rd letter will be capitalized as well changing the name to 'McCall'.


Solution

  • $name = 'mccall';
    $name = ucwords(strtolower(trim($name))) ;
    
    if (strpos($name, 'Mc') === 0) {
        $name = 'Mc' . ucwords(substr($name, 2, strlen($name)));
    }
    echo $name; // McCall