Page 1 of 1

preg_match

Posted: Tue May 18, 2010 11:31 am
by michaelk46
I am trying to make sure that the only characters in a name field from an HTML form are letters and optionally spaces if the user is so inclined to use them. The script works if there are only letters, but the optional space is giving me some fits. I think I have the preg_match search options set incorrectly, but i haven't been able to find much on setting an optional parameter for it in google.

Here is the script

Code: Select all

$name = $_POST['name'];
	if (!preg_match("/^[a-zA-Z]+(\s)?$/", $name)) //verify $name contains only letters and spaces
		{
			echo htmlspecialchars('Name field is invalid, letters and spaces only please correct and re-submit.');
			exit();
		}

Anytime a name without a space is typed in, it works fine, but once a space is inserted such as a space between a first name and last name (IE...John Smith), it errors out and says the name field is invalid. Help....please

Re: preg_match

Posted: Tue May 18, 2010 11:35 am
by AbraCadaver
A better one might be:

Code: Select all

"/[\w]+/"

Re: preg_match

Posted: Tue May 18, 2010 11:42 am
by michaelk46
Still get 'Name field is invalid, letters and spaces only please correct and re-submit.'

I was assuming that you meant that I should replace the \s with the \w
Here is the used search string i used after the replacement... "/^[a-zA-Z]+[\w]+?$/"

Re: preg_match

Posted: Tue May 18, 2010 11:47 am
by michaelk46
Nevermind... I got it... Thanks dude...

Re: preg_match

Posted: Tue May 18, 2010 11:47 am
by AbraCadaver
michaelk46 wrote:Still get 'Name field is invalid, letters and spaces only please correct and re-submit.'

I was assuming that you meant that I should replace the \s with the \w
Here is the used search string i used after the replacement... "/^[a-zA-Z]+[\w]+?$/"
No, replace the entire pattern. That's why I used quotes and delimiters :wink:

Re: preg_match

Posted: Tue May 18, 2010 8:11 pm
by michaelk46
Yeah, I finally caught that once I looked a little closer... Thanks again...I appreciate the help.