note 40508 added to function.ucfirst
| From: | LeeBenson at rn2 dot php dot net | Date: | Fri, 05 Mar 2004 19:37:18 +0000 |
| Subject: | note 40508 added to function.ucfirst | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-66322@lists.php.net to get a copy of this message | ||
Here's a function I threw together when needing to validate name entries (both first name and
last name).
This allows simple formatting for names prefixed with "Mc" (like McDonald, McCulloch, etc)
and names prefixed with O (like O'Reilly, O'Conner, etc)..
It also allows double-barrelled names to be formatted correctly, in the Smith-Jones way.
Here's the function...
<?php
function FormatName($name=NULL) {
/* Formats a first or last name, and returns the formatted
version */
if (empty($name))
return false;
// Initially set the string to lower, to work on it
$name = strtolower($name);
// Run through and uppercase any multi-barrelled names
$names_array = explode('-',$name);
for ($i = 0; $i < count($names_array); $i++) {
// "McDonald", "O'Conner"..
if (strncmp($names_array[$i],'mc',2) == 0 ||
ereg('^[oO]\'[a-zA-Z]',$names_array[$i])) {
$names_array[$i][2] = strtoupper($names_array[$i][2]);
}
// Always set the first letter to uppercase, no matter what
$names_array[$i] = ucfirst($names_array[$i]);
}
// Piece the names back together
$name = implode('-',$names_array);
// Return upper-casing on all missed (but required) elements of the $name var
return ucwords($name);
}
?>
If you have any other "rules" to follow for international/foreign naming rules, you can
add them to the foreach loop, and it should still follow all of the other rules.
It's a quick fix, but it seems to do the job nicely.
Examples...
<?php
$name = "o'cONNER-MCdOnAld";
echo FormatName($name);
?>
Returns: O'Conner-McDonald
----
Manual Page -- http://www.php.net/manual/en/function.ucfirst.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+40508
Delete -- http://master.php.net/manage/user-notes.php?action=delete+40508&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+40508&report=yes
Search -- http://master.php.net/manage/user-notes.php