Page 1 of 1

ereg_replace() / mod_rewrite

Posted: Mon Jul 02, 2007 3:33 pm
by psurrena
I currently use ereg_replace() to remove the spaces from an article title and replace them with dashes to be used in a URL. My question is what is the best method to remove all non alpha/numeric characters such as ", !, #, '? Should I store them in an array and use that, i.e. ereg_repalce($badcharacters, '') or is there a better method?

Posted: Mon Jul 02, 2007 3:44 pm
by Ambush Commander
Generally speaking, you should favor the PCRE functions (preg_replace, preg_split, preg_match) over the EREG functions because they're faster and binary-safe.

Why not try splitting the string on "bad characters" and then imploding it with a dash as the glue?

Posted: Mon Jul 02, 2007 4:06 pm
by psurrena
So turn the article title into an array? What would be the advantage?

Posted: Mon Jul 02, 2007 4:16 pm
by Ambush Commander
It would mean that "Great stuff! #23 delivers foobar?" converts to "great-stuff-23-delivers-foobar"

Posted: Mon Jul 02, 2007 4:18 pm
by superdezign
Or you could preg_replace any characters you don't allow with a dash.

Edit: And compress consecutive dashes into one, afterwards.

Posted: Mon Jul 02, 2007 4:21 pm
by Ambush Commander
That works too. If you match dashes, the compression will happen automatically. The only thing is you won't be able to get rid of trailing dashes with that method (easily, maybe some regexp-fu will make it happen)