简体   繁体   中英

Allow only English letters and numbers in php

I'm trying to create a filter to allow users to use only English letters (Lowercase & uppercase) and numbers. how can I do that? (ANSI) (not trying to sanitize, only to tell if a string contain non-english letters) That filter should get me a clean database with only english usernames, without multibyte and UTF-8 characters.

And can anyone explain to me why echo strlen(À) outputs '2'? it means two bytes right? wans't UTF-8 chars supposed to contain a single byte?

Thanks

You should use regular expressions to see if a string matches a pattern. This one is pretty simple:

if (preg_match('/^[a-zA-Z0-9]+$/', $username)) {
    echo 'Username is valid';
} else {
    echo 'Username is NOT valid';
}

And the reason why strlen('À') equals 2 is because strlen doesn't know that string is UTF-8. Try using:

echo strlen(utf8_decode('À'));

This is how you check whether a string contains only letters from the English alphabet.

if (!preg_match('/[^A-Za-z0-9]/', $string))  {
    //string contains only letters from the English alphabet
}

The other question:

strlen(À)

will not return 2. Maybe you meant

strlen('À')

strlen returns

The length of the string on success, and 0 if the string is empty.

taken from here . So, that character is interpreted as two characters, probably due to your encoding.

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