views:

312

answers:

4

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.

+2  A: 

[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

Zenon
+1 for the [] brackets :)
Sadi
oh and you could also use \s to match white space characters (space, tab, newline and so on)
Zenon
+1  A: 

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

The ^ matches the beginning of the string, which prevents it from matching the middle of the string 123abc. The $ similarly matches the end of the string, preventing it from matching the middle of abc123.
The brackets match every character inside of them; a-z means every character between a and z. To match the - character itself, put it at the end. ([19-] matches a 1, a 9, or a -; [1-9] matches every character between 1 and 9, and does not match -).
The + tells it to match one or more of the thing before it. You can replace the + with a *, which means 0 or more, if you also want to match an empty string.

For more information, see here.

SLaks
@Matt: I'm well aware of that. Think twice before downvoting.
SLaks
@SLaksInformative, though not exactly the answer. +1 :)Thank you
Sadi
+7  A: 

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 */ }
Matt
Thank you. Would you please explain the \w
Sadi
It's for standard word characters. I'm using it sort of redundantly. I believe it matches [A-Za-z0-9_] (all letters, numbers, and underscore) if I'm not mistaken.
Matt
@MattYes, that's it. :) Thank you
Sadi
A: 

You would be looking at a negated ^ character class [] that stipulates your allowed characters, then test for matches.

$pattern = '/[^A-Za-z\- ]/';
if (preg_match($pattern, $string_of_input)){
   //return a fail
}

//Matt beat me too it...
Jessedc