Make first letter uppercase and the rest lowercase in a string

user1048676 picture user1048676 · Jan 5, 2012 · Viewed 81.6k times · Source

All, I'm trying to insert a last name into a database. I'd like the first letter to be capitalized for the name and if they have use two last names then capitalize the first and second names. So for example if someone enters:

marriedname maidenname

It would convert this to Marriedname Maidenname and so on if there is more then two names. The other scenario is is someone has an apostrophe in their name, so is there anyway to do it 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. Thanks for any advice!

Answer

Paul picture Paul · Jan 5, 2012

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