[英]php regex allow only english characters in string
I want to insert into a textbox only english characters and other special characters like我想只在文本框中插入英文字符和其他特殊字符,例如
$!@{]{[
etc... ETC...
but also i want to check if the string contains at least 2 characters of these: (a-zA-Z0-9)但我也想检查字符串是否包含至少 2 个字符:(a-zA-Z0-9)
So i thought of this:所以我想到了这个:
preg_match('/[^a-zA-Z0-9 -"?()[]#:/\'_+*%@!~`$><,.;{}|\]/',$string)
is this a good approach?这是一个好方法吗?
No your approach is not good不,你的方法不好
Try this one.试试这个。 You need to complete the special characters you want into the character class.
你需要把你想要的特殊字符补全成字符class。 You need to escape the
]\-^
characters since they have special meanings in the class (depending on their position).您需要转义
]\-^
字符,因为它们在 class 中具有特殊含义(取决于它们的位置)。
^(?=.*[A-Za-z0-9].*[A-Za-z0-9])[$!@{}[\]A-Za-z0-9]*$
See it here on Regexr在 Regexr 上查看
The first part is a positive lookahead that ensures the two characters of your [A-Za-z0-9]
requirement somewhere in the string.第一部分是积极的前瞻,确保您的
[A-Za-z0-9]
要求的两个字符在字符串中的某个位置。
Then comes the character class [A-Za-z0-9])[$!@\{\}\[\]A-Za-z0-9]
where you can put in the characters that you want to match.然后是字符 class
[A-Za-z0-9])[$!@\{\}\[\]A-Za-z0-9]
,您可以在其中输入要匹配的字符。
The ^
at the beginning of my expression ensures that it matches from the start of the beginning and the $
at the end ensure that it matches the end of the string.我的表达式开头的
^
确保它从开头匹配,末尾的$
确保它匹配字符串的结尾。
The ^
at the beginning of your example is a negation of the complete character class, what you don't want I guess, if you want to match for the character ^
put it somewhere else in the class.示例开头的
^
是对完整字符 class 的否定,我猜你不想要什么,如果你想匹配字符^
把它放在 class 的其他地方。 The -
in the middle of your class defines a character range that matches everything from -"
, I don't know what characters that are, but probably more than you want. Put the -
at the beginning or the end or escape it. class 中间的
-
定义了一个与-"
中的所有内容匹配的字符范围,我不知道是什么字符,但可能比你想要的更多。将-
放在开头或结尾或转义它。
$parameter ='(a-zA-Z){2}';
if $string='kasdfhk890';
preg_match($string,$parameter); //
return false;
if $string='k';
preg_match($string,$parameter); // single char error
return false;
if $string='kuyyee';
preg_match($string,$parameter);// english character only
return true;
(?:.*?[0-9a-zA-Z]){2,}[0-9a-zA-Z$!@{\]{\[]*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.