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 开发者_StackOverflow社区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:
if(preg_match('/[^a-z0-9]/i', $search))
{
$error = "Error...";
}
The /i
flag tells the expression to ignore case, so A-Z
is 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 the if()
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:
if(preg_match('/[^a-z0-9 \.]/i', $search))
{
$error = "Error...";
}
This example allows spaces and .
(dots).
Something like this:
if(!preg_match('/^[a-zA-Z0-9]+$/', $search)) {
// error
}
精彩评论