I want to check a string to allow only a-z A-Z 0-9 . / ? & but I'm unsure how exactly to use preg_match().
If you could also explain what each part of the code is I'd appreciate it! (ie why do you add /^ and how to you add a /)
Thanks
Here it is:
$input = 'Hello...?World';
$regex = '~^[a-z0-9&./?]+$~i';
if (preg_match($regex, $input)) {
echo "yeah!";
}
You can build your own character classes and validate strings this way.
Explanation:
~
^ # string start
[ # start character class
a-z # letters from a to z
0-9 # digits from 0 to 9
&./? # &,.,/ and ? chars
] # end character class
+ # repeat one or more time
$ # string end
~ix
.?/ are not meta characters in a character class and do not need escaping. / is not a meta character anyway, it only needs escaping if you use it as a delimiter. Every character has its literal meaning except ]\^- Also you would be better to do if (!preg_match('~[^a-z0-9&./?]~i')) for simplicity and to give PCRE less to do, I feel.if ( preg_match('[^a-zA-Z0-9./?&]', 'azAZ09./?&') ) {
//found a character that does not match!
} else //regex failed, meaning all characters actually match
Pretty similar to ioseb's, but you need to include A-Z because uppercase is different from lowercase. He has written a great guide to the characters already so I'll just present an alternative regex.
I rely on negation instead (the ^ at the start, which when included at the start of a character class '[]', it has a different meaning instead), followed by the string of "allowed characters".
That way, if the regex finds anything that isn't an allowed character (the [] means one character), it'll stop parsing and return true, which means an invalid string was found.
[ and ] as delimiters is kinda awkward IMHO.