Regex question


I’m trying to make use of regular expressions to validate a form. This is my first go with it, and I thought I had the basics down from a tutorial…but I’m failing. :slight_smile:

I want to validate a first name field so that it doesn’t allow spaces or numbers. Seems pretty simple. After trying the character ranges, I’ve come to something that works but I know it can’t be right…

$regex = "[\\s]";
	$regex2 = "[\\d]";
		$error_list[] = 'First name is required';
			if(preg_match($regex, $fname))
					$error_list[] = 'First name only, no spaces please.';
			if(preg_match($regex2, $fname))
					$error_list[] = 'First name cannot have numbers.';

There’s got to be a way to only call preg_match once right? I’m just not getting how to use the character ranges.

I’ve tried [0-9] in combination with /s and /s in combo with /d, but none of those attempts have worked.

Any help or guidance is much appreciated. Thanks!

For what it’s worth (maybe you have already seen it), the PHP manual has a very detailed section [1] on the regex syntax that you’re having trouble with… take it slowly and have plenty of practice.


Thank you both. I’ll give that a try and do some more reading.

if ( preg_match( '/[\\s\\d]/', $var ) ) {
  // ... contains whitespace and or numbers.

Might want to take look at filter_input as well:

It’s good to be able to roll your own but after that it’s nice to be able to take advantage of built in functionality.