简体   繁体   中英

php regex allow only english characters in string

I want to insert into a textbox only english characters and other special characters like

$!@{]{[

etc...

but also i want to check if the string contains at least 2 characters of these: (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. You need to escape the ]\-^ characters since they have special meanings in the class (depending on their position).

^(?=.*[A-Za-z0-9].*[A-Za-z0-9])[$!@{}[\]A-Za-z0-9]*$

See it here on Regexr

The first part is a positive lookahead that ensures the two characters of your [A-Za-z0-9] requirement somewhere in the string.

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.

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. 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.

$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;

You want learn more try this link

(?:.*?[0-9a-zA-Z]){2,}[0-9a-zA-Z$!@{\]{\[]*

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM