Im creating a search function. The users are only allowed to use a-z A-Z and 0-9. How do i check if $var only contains text or numbers, and not special characters ?
I have tried something like this:
if (!preg_match('/[^a-z]/i', $search) {
$error = "error...";
}
If anyone have a smarter solution, please let me know. It could also be something checking for special characters.
You’re pretty much there. Just add numbers 0-9 to your regular expression, like this:
The
/iflag tells the expression to ignore case, soA-Zis not needed inside the letter list.In your original code, you were looking for anything that wasn’t a letter or number, while also checking to see if
preg_match()hadn’t matched anything – you created a double negative. The code above executes theif()if anything that isn’t a letter or number is found. Full credit to @brain in the comments.To allow other characters, simply add them to the characters inside the braces:
This example allows spaces and
.(dots).