I need some help with field validation

When users fill out my registration form I get all kinds of formats:

firstname lastname

Sometimes they add an extra space after their name too. Is there a good php function that will strip out extra spaces as well as use good capitalization? It needs to take into consideration names like McDowell that properly use two capital letters.


To strip out the spaces there is a function trim() in php you can use that. And to capitalize the text, [URL=“http://www.php.net/strtoupper”]strtoupper() function is used but this will capitalize all the characters. Or there is another function [URL=“http://www.php.net/manual/en/function.ucwords.php”]ucwords() which makes first character of each words in the phrase/sentence. Hope you can manage using these functions.

Is it possible for me to write some code that would check to see if the string is in uppercase, and if so, convert it? That way if the string is something like McDonell, I won’t convert it.


Which and how many characters do you want to check if they are already in uppercase? Or you want to check all the characters in a word or whole phrase?

There are several PHP functions to check for upper case characters, there is even a function {http://php.net/manual/en/function.ucfirst.php} to make the first character upper case.

If you want to allow McDonnell type names, a regexp might be more suited.

Yes, I would like to check the whole phrase to see if it’s upper case. So names like VAN ORDEN.

Have a look at http://php.net/manual/en/book.ctype.php

Specifically http://www.php.net/manual/en/function.ctype-upper.php

if (ctype_upper($name)) {
 // Name is all upper case

Can you help me understand why the output of this script is only, “testing…123” ? Here is my code:



$firstname = "BILLY JONES";

if (ctype_upper($firstname)) {

// Fix the name because it is all upper case
//$firstname	= ucwords(strtolower($firstname));  

print ("UPPERcase");


if (ctype_lower($firstname)) {

// Fix the name because it is all lower case
//$firstname	= ucwords($firstname); 

print ("lowercase");


print ("testing.....123");


The space between BILLY and JONES is considered to be neither upper or lowercase.

$firstname = trim('BILLY JONES');

if(ctype_upper(str_replace(' ', '', $firstname))) {
   echo 'UPPERcase';