Wednesday, April 6, 2011

Alphanumeric and more

So I am designing a registration page and checking the username is alphanumeric.

         else if(!eregi("^([0-9a-z])+$", $subuser)){
        $form->setError($field, "* Username not alphanumeric");

I use that to do so. Is there any way I can get that to include underscores (_), dash (-), and spaces? Thanks

From stackoverflow
  • You can use:

    else if(!eregi("^([0-9a-z_ -])+$", $subuser)){
    

    You just need to add an underscore(_), a hyphen (-) and a space( ) to the char class. Of the three only hyphen has special meaning in the char class but only if its surrounded on both sides by char. So to avoid this you can include it at the beginning or at the end. You can also include it in the middle and escape it.

    So the following are also valid:

    else if(!eregi("^([-0-9a-z_ ])+$", $subuser)){
    else if(!eregi("^([0-9a-z_\- ])+$", $subuser)){
    
    Col. Shrapnel : too bad eregi is deprecated in php.
  • You can use like this

    if(!eregi("^([0-9a-z-_ ])+$", $subuser))
    

    u can add as many special character in this bracket [0-9a-z-_ ] but be sure coz some need to be escaped by (slash)

  • it is better to learn using preg_match syntax because that is a standard regular expression check.

    with that it should be like this:

    $bValid = preg_match("/^[\w\d-_]*$/", $sUsername);
    

    for feather reading about regular expression check read http://www.php.net/manual/en/intro.pcre.php

    and for short comparison between preg_match and ereg see http://answers.yahoo.com/question/index?qid=20080327071915AAO0O2w

    Col. Shrapnel : upvoted as the only non-deprecated preg answer. Though I'd make it explicit, not classes, as \w can vary depending on locale settings.
    Col. Shrapnel : OMG remove the last one. this yahoo answer is terrible. ereg is deprecated, that's all. and the rest is junk. what the heck is "binary safe"? and for the web-page size piece of data the speed difference is insignificant
    takpar : @shrapnel i agree. updated.

0 comments:

Post a Comment