phpstringtitle-casehumanizeucfirst

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.


Solution

  • 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))));