regular expressions help

Discussion in 'PHP' started by Vizuke, Sep 11, 2006.

  1. #1
    My function is not passing true. I'm not sure if I have my expressions correct. I'm trying to limit the $value to one alphanumberics.

    function check_special_chars($value,$type) {
    	if($type==1) { $pattern="[a-zA-Z0-9]"; } //alphanumeric with caps
    	elseif($type==2) { $pattern="[a-zA-Z0-9_-]"; } //alphanumeric with underscore and dash
    	elseif($type==3) { $pattern="[0-9]"; } //0 to 9 only
    	elseif($type==4) { $pattern="[a-z]"; } //alpha lowercase only
    	if(preg_match($pattern,$value)) { return 1; }
    	else { return 0; }
    	}
    PHP:

     
    Vizuke, Sep 11, 2006 IP
  2. kjewat

    kjewat Active Member

    Messages:
    149
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #2
    kjewat, Sep 11, 2006 IP
  3. SoKickIt

    SoKickIt Active Member

    Messages:
    305
    Likes Received:
    30
    Best Answers:
    0
    Trophy Points:
    70
    #3
    function check_special_chars($value,$type) {
    	if($type==1) { $pattern="/^[a-zA-Z0-9]*$/"; } //alphanumeric with caps
    	elseif($type==2) { $pattern="/^[a-zA-Z0-9_-]*$/"; } //alphanumeric with underscore and dash
    	elseif($type==3) { $pattern="/^[0-9]*$/"; } //0 to 9 only
    	elseif($type==4) { $pattern="/^[a-z]*$/"; } //alpha lowercase only
    	if(preg_match($pattern,$value)) { return 1; }
    	else { return 0; }
    	}
    PHP:
    Maybe you should check Ctype functions and the switch statement.
     
    SoKickIt, Sep 11, 2006 IP
  4. falcondriver

    falcondriver Well-Known Member

    Messages:
    963
    Likes Received:
    47
    Best Answers:
    0
    Trophy Points:
    145
    #4
    can you give some examples what you have an what you want out of this function? afaik there is a regex expression covering all the special chars, similar to 0-9 for numbers. check out http://en.wikipedia.org/wiki/Regex and scroll down to the table with posix classes, maybe this helps.

    otherwise ask nintendo, he knows it best and will be happy to help :)
     
    falcondriver, Sep 11, 2006 IP
  5. sketch

    sketch Well-Known Member

    Messages:
    898
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    148
    #5
    Ya, it'd help to know what you're trying to match. But to add to SoKickIt's example, you need to escape the dashes as well ( \- ). And unless you want to match no characters, I'd change the star (*) to a plus (+) so it'll match 1 or more of the given characters.
     
    sketch, Sep 12, 2006 IP