SkinnyBetas
SkinnyBetas

Reputation: 501

Trying to get regex pattern to match any other than letters and single special character

I'm new to regex and am trying to match a very simple pattern but am struggling to get regex. I basically just want test a bunch of strings to check if they contain anything that isn't either in 'a-z' (both lower or upper case) or '_' character. So if a string contains the '@' character I want it to fail.

so far it looks like:

if (!preg_match("/[a-z_]/", $string)) {
     echo "Bad string";
}

But that's failing to pickup anything it seems. Any help would be greatly appreciated.

Upvotes: 1

Views: 744

Answers (1)

bassxzero
bassxzero

Reputation: 5041

Use negation in your regex to search for characters you don't want.

// If the string has any characters other than A-z or _ then echo bad string
if (preg_match("/[^a-zA-Z_]/", $string)) {
     echo "Bad string";
}

https://regex101.com/r/wKUNjm/2

Upvotes: 2

Related Questions