问题
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.
回答1:
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 */ }
回答2:
[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
回答3:
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.
回答4:
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...
来源:https://stackoverflow.com/questions/1778958/php-regular-expression-accept-selected-characters-only