Regular Expressions

Discussion in 'PHP' started by MrLeN, Jul 13, 2011.

  1. #1
    I am using this code:

    $menu_css = ereg_replace("[^A-Za-z0-9]", "", $menu_css );
    Code (markup):
    However, the code is removing spaces.

    How can I change it so that it removes everything, except spaces?
     
    MrLeN, Jul 13, 2011 IP
  2. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #2
    if you remove everything except spaces then you end up with a string containing only spaces!

    What is the point of that?

    Maybe you should explain more what you want to do.
     
    stephan2307, Jul 13, 2011 IP
  3. MrLeN

    MrLeN Well-Known Member

    Messages:
    406
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    120
    #3
    The code above only removed everything that is not a number or letter.

    However, it is also removing spaces. I do not want it to remove spaces.

    I don't want it to remove underscores either.

    Or, in other words, I want to remove everything except numbers, letters, spaces and underscores from $my_value.
     
    MrLeN, Jul 13, 2011 IP
  4. gviger

    gviger Peon

    Messages:
    38
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Try this.

    		
    $string = 'Some 1234 very big string _ with - space .';
    $allowed = "/[^a-z0-9\\ \\_\\\\]/i";
    $result_string = preg_replace($allowed,"",$string);
    Code (markup):
     
    gviger, Jul 13, 2011 IP
  5. ntomsheck

    ntomsheck Peon

    Messages:
    87
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #5
    "/[a-z0-9\s\_]/i"
    Cleaner looking.
     
    ntomsheck, Jul 13, 2011 IP
  6. suryawl

    suryawl Peon

    Messages:
    54
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    0
    #6
    use \s. it means space in regex
     
    suryawl, Jul 22, 2011 IP