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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

PHP Regex Pattern Problem

  • 20-02-2013 1: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,190 ✭✭✭✭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