Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regular Expression [accept selected characters only]

I want to accept a list of character as input from the user and reject the rest. I can accept a formatted string or find if a character/string is missing. But how I can accept only a set of character while reject all other characters. I would like to use preg_match to do this.

e.g. Allowable characters are: a..z, A..Z, -, ’ ‘ User must able to enter those character in any order. But they must not allowed to use other than those characters.

like image 693
Sadi Avatar asked Dec 23 '22 07:12

Sadi


2 Answers

Use a negated character class: [^A-Za-z-\w]

This will only match if the user enters something OTHER than what is in that character class.

if (preg_match('/[^A-Za-z-\w]/', $input)) { /* invalid charcter entered */ }
like image 128
Matt Avatar answered Dec 28 '22 06:12

Matt


[a-zA-Z-\w]

[] brackets are used to group characters and behave like a single character. so you can also do stuff like [...]+ and so on also a-z, A-Z, 0-9 define ranges so you don't have to write the whole alphabet

like image 43
Zenon Avatar answered Dec 28 '22 07:12

Zenon