RegEx- removing anything but letters, spaces, and numbers

Discussion in 'PHP' started by ForgottenCreature, Mar 31, 2006.

  1. #1
    How do I go about removing everything in a string besides letters, spaces, and digits?

    So far I have

    $newvar = ereg_replace("[^A-Za-z0-9]", "", $string);

    That takes care of the letters and digits, but not the spaces.

    Help?
     
    ForgottenCreature, Mar 31, 2006 IP
  2. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $newvar = preg_replace ('/[^a-z0-9 ]+/i', '', $string);
    PHP:
    use preg_replace because it's usually faster than it's ereg counterpart.
     
    exam, Mar 31, 2006 IP
  3. drewbe121212

    drewbe121212 Well-Known Member

    Messages:
    733
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    125
    #3
    You can also use:
    
    <?
        $newvar = preg_replace('/[^a-z0-9\s]+/i', '', $string);
    ?>
    
    Code (markup):
     
    drewbe121212, Apr 11, 2006 IP
  4. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Good call, and Welcome to the forums Drew! :)
     
    exam, Apr 11, 2006 IP