php 只允许使用 pregmatch 的字母、数字、空格和特定符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17085738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php only allow letters, numbers, spaces and specific symbols using pregmatch
提问by CudoX
on my php i use preg_match
to validate input texts.
在我的 php 上,我preg_match
用来验证输入文本。
if(preg_match('/^[a-zA-Z0-9]+$/', $firstname)) {
}
But this only allows alphanumeric and does not allow spaces. I want to allow spaces, alpha and numeric. and period(.) and dash(-)
但这仅允许字母数字,不允许空格。我想允许空格、字母和数字。和句号(.) 和破折号(-)
Please help me out here? thanks in advance.
请帮我看看这里?提前致谢。
回答by Baba
Use
用
preg_match('/^[a-z0-9 .\-]+$/i', $firstname)
回答by stema
If you not only want to allow ASCII, then use Unicode properties:
如果您不仅要允许 ASCII,请使用Unicode 属性:
preg_match('/^[\p{L}\p{N} .-]+$/', $firstname)
\p{L}
is any letter in anylanguage, matches also Chinese, Hebrew, Arabic, ... characters.
\p{L}
在任何字母的任何语言,也符合china,希伯来语,阿拉伯语,...字符。
\p{N}
any kind of numeric character (means also e.g. roman numerals)
\p{N}
任何类型的数字字符(也意味着例如罗马数字)
if you want to limit to digits, then use \p{Nd}
如果你想限制为数字,然后使用 \p{Nd}
回答by Spudley
The only difficult bit here is the dash.
这里唯一困难的是破折号。
For spaces and dots, you can simply add them to your character class, like so:
对于空格和点,您可以简单地将它们添加到您的字符类中,如下所示:
'/^[a-zA-Z0-9 .]+$/'
Easy.
简单。
The dash is slightly harder because hyphens have special meaning in a character class like this (as you already know, they're used for ranges of characters like a-z
). In order to specify a hyphen in a character class, it must be the first character in the class (ie it must not be between two characters, otherwise it is treated as a character range marker).
破折号稍微难一些,因为连字符在这样的字符类中具有特殊含义(如您所知,它们用于诸如 之类的字符范围a-z
)。为了在字符类中指定连字符,它必须是类中的第一个字符(即它不能在两个字符之间,否则将被视为字符范围标记)。
So your expression would be:
所以你的表达是:
'/^[-a-zA-Z0-9 .]+$/'
Hope that helps.
希望有帮助。