I am using preg_match for restrict the special characters in form post. Now I need to restrict some special characters only like %,$,#,*
and I need to post like bé
. How to possible to restrict some special characters only.
My code:
<?php
$firstname='';
if(isset($_POST['submit']))
{
$firstname=$_POST['firstname'];
if(preg_match("/[^a-zA-Z0-9]+/", $firstname))
{
echo 'Invalid Name';
}
else
{
echo $firstname;
}
}
?>
<html>
<body>
<form method="post">
<input type="text" name="firstname"/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Blacklisting (=enumerating invalid characters) is not an option in the unicode world. Consider for example, a "name" like this:
Ж☝ⓚƒ
You don't really want to blacklist all of these.
A whitelisting approach is, on the contrary, quite simple using the u
mode and unicode properties:
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'ßäßå')); // 1
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'r2d2')); // 1
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'w#t?')); // 0
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'Ж☝ⓚƒ')); // 0
And since we're talking about validating real names, please read Falsehoods Programmers Believe About Names before you start complicating things.
You should use:
([%\$#\*]+)
to match those characters.
So in preg_match
you should use:
if(preg_match("/([%\$#\*]+)/", $firstname))
{
echo 'Invalid Name';
}
else
{
echo $firstname;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.