#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2009
    Posts
    1
    Rep Power
    0

    Remove Alphanumerics Except for +


    I need some help, guys. This is the first time I've had to work with regex, and it's kicking my butt right now.

    This function is currently taking out all the non-alphanumeric characters from a URL in a URL rewrite and caching script I am using. But I want to change the regex so that the + symbol remains.

    Here's the original function:
    Code:
    function removeNonAlphaNumeric($name, $name_delimiter){
                           return preg_replace("/[^a-zA-Z0-9]/", $name_delimiter, $name);
                   }

    I've already tried this without success:
    Code:
    function removeNonAlphaNumeric($name, $name_delimiter){
                           return preg_replace("/[^a-zA-Z0-9\+]/", $name_delimiter, $name);
                   }
    Any ideas?
  2. #2
  3. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,127
    Rep Power
    4304
    Welcome to DevShed Forums, mattmauldin.

    Try this:
    Code:
    function removeNonAlphaNumeric($name, $name_delimiter){
                           return preg_replace("/[^a-zA-Z0-9\+\040]/", $name_delimiter, $name);
                   }
    The "\040" means a space character.
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).
  4. #3
  5. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,112
    Rep Power
    9398
    I'd recommend adding a + (as in repetition):
    Code:
    /[^...]+/
    Without, "Programming Languages - More" could turn into "Programming-Languages---More".
    With, you get "Programing-Languages-More".

    I'd also recommend trimming off the $name_delimiter from the start and end.
    Code:
    "Programming Languages (More)"     before
    -> "Programming-Languages-More-"   after regex
    -> "Programming-Languages-More"    after trim

    Comments on this post

    • Kravvitz agrees

IMN logo majestic logo threadwatch logo seochat tools logo