Arabic characters using preg_match() function

2019-07-26 00:07发布

问题:

I am trying to use preg_match() to check Arabic and English characters only,

i used this code:

preg_match("/^[a-zA-Zأ-ي]*$/",$name)

but still, it is not working.

EDIT: The code that does not work:

if($name == '' || $email =='') {
    echo("<div class=\"error\">fill all fields</div>");
}
else if (!preg_match("/^[a-zA-Zأ-ي\s]*$/",$name)) {
     echo("<div class=\"error\">Only letters and white space allowed</div>");
}
else if (strlen($name) < 6) {
    echo("<div class=\"error\">NONONONO les than 6</div>");
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo("<div class=\"error\">WORNG EMAIL</div>"); 
} else {}

回答1:

You need to use a /u modifier with preg_match to make sure the pattern and string are treated as Unicode strings and the strlen must be replaced with mb_strlen to correctly count Unicode characters:

else if (!preg_match("/^[a-zA-Zأ-ي\s]*$/u",$name)) {
     echo("<div class=\"error\">Only letters and white space allowed</div>");
}
else if (mb_strlen($name) < 6) {
    echo("<div class=\"error\">NONONONO les than 6</div>");
}