How to use ctype_alpha with UTF-8

2019-07-20 09:33发布

问题:

How to use ctype_alpha with UTF-8?

I have this code:

if(empty($_POST) === false) {      
    if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
        if (ctype_alpha($_POST['first_name']) === false) {
            $errors[] = 'Please enter your First Name with only letters!';
        }   
    }
}

Here I check if everything is fine. If not I get an error.

But if I use letters like ščćž - UTF-8 then I also get errors. So how I can solve this problem? I need for first names to have letters only but UTF-8 characters like ščćž must be allowed.

回答1:

Use regex for latin characters, change this condition:

if (ctype_alpha($_POST['first_name']) === false)

to:

if (!preg_match('/^[\p{Latin}]+$/u', $_POST['first_name'])

Or - to allow whitespace:

if (!preg_match('/^[\p{Latin}\s]+$/u', $_POST['first_name'])


标签: php utf-8