Clean Capitalising of Names

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
johnsmith153
Forum Newbie
Posts: 10
Joined: Thu Feb 14, 2008 6:53 am

Clean Capitalising of Names

Post by johnsmith153 »

I need a script to capitalize people's names.

Ie someone enters jiM mCDonalD - it returns Jim McDonald

Below sets all to lower case and then changes first lettter - but I get Jim Mcdonald (ie some letters should / should not be capitalised)

I am not bothered about the 0.1% of weird names, but there are a lot of Mc names about etc.

Anyone got a script hanging around?

Code: Select all

 
 
<?php
 
//first, converts to lower case, then sets first letter as capital (must set first to lowercase)
 
$name = "jim brown";
 
$name2 = strtolower($name);
 
$name3 = ucwords($name2);
 
echo $name3;
 
?>
 
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Clean Capitalising of Names

Post by Christopher »

I would suggest exploding on spaces and loop through the names doing a preg check for mac, mc, d', etc. to check for the exceptions.
(#10850)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Clean Capitalising of Names

Post by Chris Corbyn »

Do what you're doing, then clean up with something like this:

Code: Select all

function upperCase($matches) {
  return strtoupper($matches[0]);
}
 
echo preg_replace_callback('/(?<=Mc)[a-z]/', 'upperCase', $convertedName);
If you want to convert more than just the Mc's then you'd need to add some alternative pipes like this:

Code: Select all

echo preg_replace_callback('/(?<=Mc)[a-z]|(?<=Mac)[a-z]/', 'upperCase', $convertedName);
As your requirements begin to grow I don't see it scaling too well however ;)
User avatar
puke7
Forum Newbie
Posts: 12
Joined: Sat May 10, 2008 11:49 am

Re: Clean Capitalising of Names

Post by puke7 »

I found this in my code library. I used it to fix some ugly song title entries in a karaoke website database. I don't really remember anything other than that.

Code: Select all

function ucTitle($string) {
  $string = strtolower($string);
  $string = join(" ", array_map('ucwords', explode(" ", $string)));
  $string = join(".", array_map('ucwords', explode(".", $string)));
  $string = join("(", array_map('ucwords', explode("(", $string)));
  $string = join("[", array_map('ucwords', explode("[", $string)));
  $string = join("/", array_map('ucwords', explode("/", $string)));
  $string = join("-", array_map('ucwords', explode("-", $string)));
  $string = join("Mac", array_map('ucwords', explode("Mac", $string)));
  $string = join("Mc", array_map('ucwords', explode("Mc", $string)));
  return trim($string);
}
Post Reply