ereg_replace() / mod_rewrite

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

ereg_replace() / mod_rewrite

Post 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?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post 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?
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Post by psurrena »

So turn the article title into an array? What would be the advantage?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

It would mean that "Great stuff! #23 delivers foobar?" converts to "great-stuff-23-delivers-foobar"
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Or you could preg_replace any characters you don't allow with a dash.

Edit: And compress consecutive dashes into one, afterwards.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post 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)
Post Reply