1

I'm using regex (I think that's what it's called - haha) to check my users' name to make sure it's valid. I want to make sure that the user doesn't have any characters. Just letters and spaces. I've got the only letters part down, but I can't get the spaces part fixed.

Here's what I'm using now..

if(preg_match("/[^a-zA-Z]/", " ", $name) != 0) {

        $errorlist = $errorlist."<li>You must enter a valid First and Last name (check for invalid characters)</li>";

}

Anyone see what I'm doing wrong?

2
  • you probably could use \s Commented May 15, 2013 at 0:22
  • Can't use \s - that matches all whitespace characters Commented May 15, 2013 at 0:22

1 Answer 1

1

Just add a space to your regex pattern. PS - your second parameter for preg_match() should probably be $name, right? Is there a reason you were testing " "?

if(preg_match("/[^a-zA-Z ]/", $name) != 0) {
    $errorlist = $errorlist."<li>You must enter a valid First and Last name (check for invalid characters)</li>";
}
Sign up to request clarification or add additional context in comments.

5 Comments

I didn't know it was that easy! Thanks!
@Fred - The reason you want to use a space character here instead of \s is that the latter would allow tabs and carriage returns in addition to spaces.
@StevenMoseley I deleted my question. I noticed it right after. Good call ;-) cheers
@StevenMoseley Would it also need to have a space after a-z?
@Fred - No. The pattern only requires a single representation of each character to match. In this case, we're saying "match NOT (all characters between a and z, all characters between A and Z, and spaces)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.