Mike Rifgin
Mike Rifgin

Reputation: 10745

validate a string consiting only of letters, numbers and optional spaces

I have this function:

function validate_string_spaces_only($string) {
    if(preg_match("/^[\w ]+$]/", $string)) {
        return true;
    } else {
        return false;
    }
}

I want to match a string that consists only of letters and numbers with an optional space character. When I feed the above function a string containing only letters, numbers and spaces it fails every time. What am I missing?

Upvotes: 2

Views: 1682

Answers (2)

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

This regex will:

  • match a string that consists only of letters and numbers with an optional space character

^[a-zA-Z0-9\s]+$

enter image description here

Upvotes: 1

Amber
Amber

Reputation: 526563

You have an extra ] character in your regex near the end. Remove it and it should work.

"/^[\w ]+$]/" should be "/^[\w ]+$/".

(Also note that \w typically allows underscores as well, which you may or may not want.)

Upvotes: 2

Related Questions