[英]How can I restrict some special characters only in PHP?
I am using preg_match for restrict the special characters in form post.我正在使用 preg_match 来限制表单帖子中的特殊字符。 Now I need to restrict some special characters only like
%,$,#,*
and I need to post like bé
.现在我需要限制一些特殊字符,比如
%,$,#,*
并且我需要像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.黑名单(=枚举无效字符)在 unicode 世界中不是一个选项。 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:相反,白名单方法非常简单,使用
u
模式和 unicode 属性:
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:所以在
preg_match
你应该使用:
if(preg_match("/([%\$#\*]+)/", $firstname))
{
echo 'Invalid Name';
}
else
{
echo $firstname;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.