[solved with solution] using preg_match to validate 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
User avatar
dallasx
Forum Contributor
Posts: 106
Joined: Thu Oct 20, 2005 4:55 pm
Location: California

[solved with solution] using preg_match to validate names

Post by dallasx »

I'm trying to error check someone's name they've entered into my site. I want to search the string and return true if the string contains only letters a-z A-Z and 1 or 2 spaces since names are only comprised of letters and spaces.

How do I do that?

Much appreciated.

EDIT: Ok, I figured it out. This particular script will look for either a name with one space or two spaces and will return TRUE only if each part contains letters of either case.
  • John Smith or John von Smith.

Code: Select all

$name_with_one_space = "/^\b[a-zA-Z]+\b\s\b[a-zA-Z]+\b$/";
$name_with_two_spaces = "/^\b[a-zA-Z]+\b\s\b[a-zA-Z]+\b\s\b[a-zA-Z]+\b$/";

if ((preg_match($name_with_one_space, $name)) or (preg_match($name_with_two_spaces, $name)))
	{
		echo "+ A match was found.";
} else {
   echo "- A match was not found.";
}
Let me know what yall think of this solution.

Thanks!
Post Reply