Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

PHP Regex Pattern Problem

  • 20-02-2013 02:23PM
    #1
    Registered Users, Registered Users 2 Posts: 1,991 ✭✭✭


    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, Registered Users 2 Posts: 68,173 ✭✭✭✭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, Registered Users 2 Posts: 1,657 ✭✭✭komodosp


    This one is handy...

    http://regexpal.com/


Advertisement