简体   繁体   中英

preg_match: All characters must match

I have an user input which gets checked if the chars are on the whitelist.

My regular expression:

[A-Za-z0-9_~\-!@#\s\$%\^&\*\(\)\=\:\;\+\°\´\[\]\{\}\§\"\'\ß\ä\ö\ü\%\.\,\>\<\|\€]+$

My code part:

$check = preg_match($pattern, trim($input));

Now, when the $input variable has for example the value abc²³ , the input gets blocked. But when it has the value abc²³def , the content won't get blocked.

How can I check every character of a string?

You simply forgot the start of string anchor: ^

^[\p{L}\d_~\-!@#\s$%^&*()=:;+°´\[\]{}§"'%.,><|€]+$

I also simplified the regex. Note that I replaced A-Za-Zßäöü with \\p{L} which will accept letters from any language.

You have to anchor the regex at the begining:

^[A-Za-z0-9_~\-!@#\s\$%\^&\*\(\)\=\:\;\+\°\´\[\]\{\}\§\"\'\ß\ä\ö\ü\%\.\,\>\<\|\€]+$

You also may simplify a bit:

^[\w~\-!@#\s$%\^&*()=:;+°´\[\]{}§"'ßäöü%.,><|€]+$

Or, even, using unicode properties:

^[-\p{L}\p{N}_~!@#\s$%\^&*()=:;+°´\[\]{}§"'%.,><|€]+$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM