Alexand657
Alexand657

Reputation: 113

preg_match only letters, spaces and dashes and spaces allowed

i know that one condition that im currently using where it gives an error if $stringabc contains anything but numbers is :

if(preg_match("/[^0-9]/",$stringabc))

I want an if condition where it gives an error if $stringdef contains anything but letters, spaces and dashes (-).

Upvotes: 7

Views: 33651

Answers (3)

DrinkJavaCodeJava
DrinkJavaCodeJava

Reputation: 808

If you want to stop all whitespace, another way you could do it is

preg_match("/^[a-z[[:space:]]-]/i",$stringabc);

Upvotes: 0

jeroen
jeroen

Reputation: 91734

You can use something like:

preg_match("/[^a-z0-9 -]/i", $stringabc)

Upvotes: 2

mvds
mvds

Reputation: 47034

That would be:

if(preg_match('/[^a-z\s-]/i',$stringabc))

for "anything but letters (a-z), spaces (\s, meaning any kind of whitespace), and dashes (-)".

To also allow numbers:

if(preg_match('/[^0-9a-z\s-]/i',$stringabc))

Upvotes: 11

Related Questions