convert a string and use it as part of URL

Discussion in 'PHP' started by shadow_boi, Dec 9, 2008.

  1. #1
    Hi,

    I am wondering if there a build-in fuction that take a string as input and then replace every non-numbers, non-alphabet characters with "_" (underscore)?

    Eg: yes? or no! will be converted to yes__or_no (i will use it as part of the URL)


    I guess regular expression can do the trick?
    Would anyone please give me the codes?

    Thanks.
     
    shadow_boi, Dec 9, 2008 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Try a preg_replace to do it.

    Something like:
    $new_string = preg_replace("/\W/s","_",$string);

    or
    $new_string = preg_replace("/[^a-Z0-9]+/","_",$string);
     
    jestep, Dec 9, 2008 IP
  3. shadow_boi

    shadow_boi Peon

    Messages:
    374
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the reply.

    the first solution works, but the second one doesnt.

    Warning: preg_replace() [function.preg-replace]: Compilation failed: range out of order in character class at offset 4
     
    shadow_boi, Dec 9, 2008 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    I would just go with the first then. It's more stable anyway.
     
    jestep, Dec 9, 2008 IP