PHP regex [accept only selected characters]

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

eg. Valid characters are: a..z, A..Z, -, 'The user must be able to enter this character in any order. But they should not be allowed to be used other than these characters.

+4
source share
4 answers

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

This will only correspond to the fact that the user enters something OTHER than what is in this character class.

if (preg_match('/[^A-Za-z-\w]/', $input)) { /* invalid charcter entered */ } 
+8
source

[A-Za-Z- \ w]

Brackets

[] are used to group characters and behavior as one character. so you can also do things like [...] + etc. also az, AZ, 0-9 define ranges, so you don't need to write the whole alphabet

+2
source

You can use the following regular expression: ^[a-zA-Z -]+$ .

^ matches the beginning of the line, which prevents it from aligning the middle of the line 123abc . $ matches the end of a line similarly, preventing it from matching the middle of abc123 .
The brackets correspond to each character within them; az means every character between a and z . To match the character itself - place it at the end. ( [19-] matches a 1 , a 9 or - ; [1-9] matches each character between 1 and 9 and does not match - ).
+ reports that it corresponds to one or more things in front of him. You can replace + with * , which means 0 or more if you also want to match an empty string.

For more information see here .

+1
source

You would look at the negative ^ character class [] , which specifies your valid characters, and then checks for compliance.

 $pattern = '/[^A-Za-z\- ]/'; if (preg_match($pattern, $string_of_input)){ //return a fail } //Matt beat me too it... 
0
source

All Articles