TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Script Giveaway (http://www.talkphp.com/script-giveaway/)
-   -   Example: Check Usernames (http://www.talkphp.com/script-giveaway/3184-example-check-usernames.html)

Oilik 07-27-2008 05:29 PM

Example: Check Usernames
 
This is a simple function I made to check if a string is a valid username or not. If it has illegal characters not specified, it'll return false/nothing, and if it's valid it'll return true/1.

PHP Code:

<?php
function isValid($string){
    
$string str_replace("_","",$string);
    
$string str_replace(" ","",$string);
    
$string str_replace(".","",$string);
    
$string str_replace("-","",$string);
        if(
ctype_alnum($string)){
            return 
true;
        }else{
            return 
false;
        }
}
?>

This is easier to remember than preg_replace for me :(
I've never quite understood that function...

delayedinsanity 07-27-2008 07:45 PM

PHP Code:

return preg_match('~^[A-Za-z][A-Za-z0-9_]{3,29}$~'$szString) ? TRUE FALSE

Username must be between 4 to 30 characters in length, may contain letters, numbers or underscores, but must start with a letter.
-m

Oilik 07-27-2008 07:47 PM

Quote:

Originally Posted by delayedinsanity (Post 17397)
PHP Code:

return preg_match('~^[A-Za-z][A-Za-z0-9_]{3,29}$~'$szString) ? TRUE FALSE

Username must be between 4 to 30 characters in length, may contain letters, numbers or underscores, but must start with a letter.
-m

Woah.. Thanks, thats useful. Intense too. :P

sketchMedia 08-07-2008 10:32 AM

I think that could be further condensed:
PHP Code:

return preg_match('/^[a-z][\w]{3,29}$/i'$szString) ? true false

'\w' stands for "word character" and is the same as [A-Za-z0-9_](including underscores)
and the 'i' at the end of the expression (after the trailing '/') makes it case insensitive.
If you want to enforce a capital at the start of the username just remove the 'i' and change the '[a-z]' to '[A-Z]' or vice-versa

To actually strip the chars specified in your function from the string with preg_replace:
PHP Code:

echo preg_replace('/[_.-\s]/''$1'$szString); 

should do it


All times are GMT. The time now is 02:36 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0