Wordpress Themes - Valentine Gifts For Him - Credit Cards - Just Holden Commodores - Flash Games

PDA

View Full Version : convert a string and use it as part of URL


shadow_boi
Dec 9th 2008, 11:13 am
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.

jestep
Dec 9th 2008, 11:39 am
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);

shadow_boi
Dec 9th 2008, 12:03 pm
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

jestep
Dec 9th 2008, 12:12 pm
I would just go with the first then. It's more stable anyway.