tags:

views:

34

answers:

3

Hello,

How can I check that username contains only english letters, punctuation symbols and digits?

Thank you.

+4  A: 
preg_match('/^[a-z0-9\p{P}]*$/i', $subject);

This will return 1 if $subject is composed only of English letters, digits and punctuation. Otherwise, it'll return 0.

Artefacto
+2  A: 

You can use regular expressions:

<?php
 $username1 = 'user.03';
 $username2 = 'c@fé';

 if(preg_match('/[^0-9A-Z.!`&\'-]/i',$username1))
   echo 'fail';
 else
   echo 'pass';

 if(preg_match('/[^0-9A-Z.!`&\'-]/i',$username2))
   echo 'fail';
 else
   echo 'pass';
?>

This will refuse any character that are not: digits, regular letters (without accents), or . ! ` & ' -

Weboide
+1  A: 

For microoptimzers:

!isset($username[strcspn($username, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?:`&\'"-')]);

(DON'T USE THAT!)

(Would love to know how much faster it is compared to RegExp...)

nikic