Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow parentheses and other symbols in regex

I've made this regex:

^[a-zA-Z0-9_.-]*$

Supports:

letters [uppercase and lowercase]
numbers [from 0 to 9]
underscores [_]
dots [.]
hyphens [-]

Now, I want to add these:

spaces [ ]
comma [,]
exclamation mark  [!]
parenthesis [()]
plus [+]
equal [=]
apostrophe [']
double quotation mark ["]
at [@]
dollar [$]
percent [%]
asterisk [*]

For example, this code accept only some of the symbols above:

^[a-zA-Z0-9 _.,-!()+=“”„@"$#%*]*$

Returns:

Warning: preg_match(): Compilation failed: range out of order in character class at offset 16

like image 984
youmotherhaveapples Avatar asked Sep 06 '13 14:09

youmotherhaveapples


1 Answers

Make sure to put hyphen - either at start or at end in character class otherwise it needs to be escaped. Try this regex:

^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]*$

Also note that because * it will even match an empty string. If you don't want to match empty strings then use +:

^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]+$

Or better:

^[\w .,!()+=`,"@$#%*-]+$

TEST:

$text = "_.,!()+=,@$#%*-";
if(!preg_match('/\A[\w .,!()+=`,"@$#%*-]+\z/', $text)) {
   echo "error.";
}
else {
   echo "OK.";
}

Prints:

OK.
like image 71
anubhava Avatar answered Oct 06 '22 02:10

anubhava