Preg_match

Discussion in 'PHP' started by Greenmethod, Feb 15, 2008.

  1. #1
    What is the best way with preg_match to filter each character for numeric digets only? This is what I have, but it only filters the first and last diget:

    preg_match('/\D+$/',$var)
    PHP:
    Thanks in advance!
     
    Greenmethod, Feb 15, 2008 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Not sure if I understand you correctly. Do you want to check if a string contains only numbers:
    
    ctype_digit($string);
    
    PHP:
    Or do you want to replace all non-numeric characters?:
    
    $string = preg_replace('~\D~', '', $string);
    
    PHP:
     
    nico_swd, Feb 15, 2008 IP
  3. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #3
    What do you mean by "filter"?

    First of all, placing "$" in it will mean that what you're searching for HAS to be right at the end of the string, which is why it's probably only working with your last digit (and the one before it?). If you also want to make sure it's at the beginning, meaning, it has to be beginning to end, put "^" at the front of the match expression.

    preg_match('/^\D+$/',$var)
    PHP:
     
    zerxer, Feb 15, 2008 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    The upper case D matches anything that's NOT numeric. Plus, ctype_digit() is faster if you want to check if a string has only numeric values.
     
    nico_swd, Feb 15, 2008 IP
  5. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Ah. I don't really use those types of vars, like D and such. I would've suggested using [0-9]+ if he's trying to find a number.

    Yeah, you're right, ctype_digit would be the best method if that's what he meant by filter. Never used that function before either.
     
    zerxer, Feb 15, 2008 IP
  6. Greenmethod

    Greenmethod Peon

    Messages:
    112
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I have some text boxes that i want to make sure is a number, nothing else. I think that ctype_digit is what I am looking for, so i'll give it a try! Thanks for your help!
     
    Greenmethod, Feb 15, 2008 IP