i’m a noob in regular expressions. Il would like to prevent a form for special characters.
The characters auhorized are :
^#{}()<>|_æ+@%.,?:;"~/=*$£€!
I made a preg_match rule that makes problems
if(preg_match("#[^#{}()<>|_æ+@%.,?:;"~/=*$£€!]+#",$input)) $error=1;
I know that i should encapsulate special chars but i didn’t know to achieve this.
Can you help me please ? Thanks in advance.
Advertisement
Answer
You can use
preg_match('/[^#{}()<>|_æ+@%.,?:;"~/=*$£€!]+/u', $input)
Note:
- Using double quotation marks inside single-quoted string literals allows to avoid extra escaping
- When you use a specific char as a regex delimiter char, here you used
#
, you must escape this char inside the pattern.
Note #
is safe to always escape since it is a special regex metacharacter when the x
flag is used to enable comment/verbose/free-spacing mode (it is called in a lot of ways across regex references/libraries).
Also, since you are using chars from outside ASCII chars, it is good idea to add u
flag (to support Unicode strings as input).