PHP Regular Expression [accept selected characters only]

php, preg-match, regex, string, validation

Solution

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 */ }

Problem

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.

Original source