Need help with checking php name entry

Discussion in 'PHP' started by offthedome, Sep 17, 2010.

  1. #1
    I need to write a preg_match function that checks the values of an input. The input will essentially be a name, but I want to allow it to have letters, numbers, and any non-dangerous symbols like dashes, commas, periods, and ampersands.

    How do I do that?
     
    offthedome, Sep 17, 2010 IP
  2. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #2
    Try this code:

    
    preg_match("/[^a-z0-9_-]/i", trim($_POST["name"]));
    
    PHP:
     
    s_ruben, Sep 17, 2010 IP
  3. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #3
    if (preg_match('#^[a-z0-9\-_,\.&]+$#iD', trim($name))) {
    //valid
    } else {
    //invalid
    }
    PHP:
    That would assume if the $name contains only those characters between the [...] (take no notice of the backslashes) and is alteast 1 character to be valid.
     
    danx10, Sep 18, 2010 IP
  4. offthedome

    offthedome Active Member

    Messages:
    446
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    95
    #4
    Would the following then allow parentheses, tildes, and that funny apostrophe under the tilde?

    if (preg_match('#^[a-z0-9\-_,\(\)\~\`\.&]+$#iD', trim($name))) {
    //valid
    } else {
    //invalid
    }
    PHP:
     
    offthedome, Sep 22, 2010 IP
  5. offthedome

    offthedome Active Member

    Messages:
    446
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    95
    #5
    Oh, and what about spaces?
     
    offthedome, Sep 22, 2010 IP
  6. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #6
    
    if (preg_match('#^[a-z0-9\-_,\.&\(\)~` ]+$#iD', trim($name))) {
    //valid
    } else {
    //invalid
    }
    PHP:
    Use that, you don't need to backslash/escape every character but only specific characters (this can be confusing at first but don't worry) - the specific characters are the following (they've been seperated with a space for readability):

    . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

    Theirfore if any of the above are used add a backslash before the character example; if I was to use the question mark; \?
     
    danx10, Sep 22, 2010 IP