PHP: Validation of user input using regex not working
this is my first attempt at writing a php regex. I'm stuck now and even though I read through what felt 28.925 regex threads here, I couldn't come up with a solution. I would really appreciate some hint by experienced developers.
Scenario:
The User is to fill out a textarea in a form on a website (form.php). Upon clicking the submit button, the filter function gets called and the string should be validated using regex to filter undesired characters. If it fails, it should give an error and abort.
The Problem:
Upon clicking submit, everything gets submitted, even though the input is something like § $ %. So nothing gets filtered. I'm clueless as to why.
My Code:
<?php
$pattern = "/^[a-zA-Z0-9]+$/";
function filter() {
$val = $_POST['nameoftextarea'];
$lines = preg_split($pattern, $val);
for($i = 0;$i < strlen($lines); $i++) {
if (preg_match($pattern, $lines[$i])) {
echo ('<p>Please delete these characters: ' . $lines[$i] . ' and try again.</p>');
return false;
}
return true;
}
}
?>
Anyone spoting any potential problems?
It seems you have forgotten a !
to negate the preg_match in the if condition.
However, there a more simple way to do that:
function filter($str) {
if (preg_match_all('~[^a-zA-Z0-9]~', $str, $matches)) {
echo '<p>Please delete these characters: '
. implode(',', array_unique($matches[0])) . ' and try again.</p>';
return false;
} else return true;
}
$boolres = filter ($_POST['nameoftextarea']);
Note: a good idea is to check the field and display warnings in the client side (HTML5 regex, Javascript) and after to control the content in the server side (PHP)
链接地址: http://www.djcxy.com/p/92706.html