Page 1 of 1

Clean Capitalising of Names

Posted: Sat May 10, 2008 6:20 pm
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;
 
?>
 
 

Re: Clean Capitalising of Names

Posted: Sat May 10, 2008 6:30 pm
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.

Re: Clean Capitalising of Names

Posted: Sat May 10, 2008 9:16 pm
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 ;)

Re: Clean Capitalising of Names

Posted: Sun May 11, 2008 7:53 pm
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);
}