preg_replace to allow special characters

Discussion in 'PHP' started by muaazab, Oct 12, 2009.

  1. #1
    Hello

    I am using following code to allow characters like A to Z and numeric values like 0 to 9.

    $result = preg_replace('/[^a-zA-Z0-9_]/', '', $result);

    In case allow only numeric values I use

    $result = preg_replace("[^0-9]","", $string);

    Actually I need preg_replace to allow A-Z plus 0-9 and some special characters like < > / @ & and white spaces.

    Is there any way in preg_replace to do so?

    Any help please? Thanks!
     
    muaazab, Oct 12, 2009 IP
  2. superdav42

    superdav42 Active Member

    Messages:
    125
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #2
    Perhaps it´s easier than you think:
    
    $result = preg_replace("/[^!<>@&\/\sA-Za-z0-9_]/","", $string);
    
    PHP:
    just put the chars you want to not remove in the [] and you be fine. You have to escape the / with \/ otherwise it will change the regex.
     
    superdav42, Oct 12, 2009 IP
  3. muaazab

    muaazab Member

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #3
    Yea this is what I actually wanted.

    Thank You superdav42.
     
    muaazab, Oct 12, 2009 IP