Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP Regex Pattern Problem

Options
  • 20-02-2013 2:23pm
    #1
    Registered Users Posts: 1,987 ✭✭✭


    I'm taking two pieces of text and using them to build a file name.

    So say I have:

    1234 and 'Is this a, test?'

    I'm looking to use preg_replace to replace all spaces with a dash and to remove all to remove all non-alphanumeric characters(except dashes).

    I have this but I can't seem to get it working, anyone any ideas or help?!
    preg_replace("[^a-zA-Z0-9/\s.(/\s+/)*]","-",'1234 Is this a, test?')
    


Comments

  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    You'll need to do it in two steps really. First step, strip out everything except non-alpha characters and spaces.
    $newString = preg_replace("/[^a-zA-Z0-9\s]/", "", $oldString);
    

    Then replace all spaces with dashes (the below will replace a series of spaces with a single dash)
    $newerString = preg_replace("/\s+/", "-", $newString);
    

    Of course you can combine them into one statement, but it can be quite unreadable.
    $newString =  preg_replace("/\s+/", "-", (preg_replace("/[^a-zA-Z0-9\s]/", "", $oldString));
    

    It's useful to get a regex testing utility (there are loads of browser plugins for it) as creating the correct regex is usually the hardest part of this code.


  • Registered Users Posts: 1,657 ✭✭✭komodosp


    This one is handy...

    http://regexpal.com/


Advertisement