How to use ctype_alpha with UTF-8

2019-07-20 09:20发布

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.

标签: php utf-8
1条回答
我命由我不由天
2楼-- · 2019-07-20 09:56

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'])
查看更多
登录 后发表回答