help using preg_replace :)

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
mischievous
Forum Commoner
Posts: 71
Joined: Sun Apr 19, 2009 8:59 pm

help using preg_replace :)

Post by mischievous »

Ok... so im creating a function that will setup a product name for an url

I need preg_replace() to basically search through the product name and replace any special charecters represent as (® etc. etc. ) so my thought is that i could setup a preg_replace function to look for the "&" charecter and the ";" and replace the block with nothing? Any ideas? because putting the full list of special characters in a pattern/replace array or what not is ridiculous

Thanks,
:dubious:
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: help using preg_replace :)

Post by Jonah Bron »

If you are just trying to remove HTML special characters, then this regex pattern will work perfectly:

/\&.*?\;/
  • The forward slashes at the beginning and the end, show that this string is a regular expression pattern
  • The first backslash is the escape character for the ampersand
  • Dot represents any character, asterisk shows that it can repeat as many times as necessary
  • The question mark says that it should make that number of repetitions as small as possible
  • The last backslash escapes the semicolon
Note, if the pattern is separated from it's surroundings by spaces, it will leave two spaces there.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: help using preg_replace :)

Post by requinix »

There's also html_entity_decode...
mischievous
Forum Commoner
Posts: 71
Joined: Sun Apr 19, 2009 8:59 pm

Re: help using preg_replace :)

Post by mischievous »

Was able to get this working with the following code:

Code: Select all

preg_replace("/&#?[a-z0-9]{2,8};/i","", $string);
*Note for htmlentities(): I tried using this and it simple took the "&" out and ";" and left the rest.

Thanks for everyones input on this matter! I appreciate it a ton! :D
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Post by Jonah Bron »

Great. BTW, you should add A-Z to that, just in case.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re:

Post by requinix »

Jonah Bron wrote:Great. BTW, you should add A-Z to that, just in case.
He did - the /i makes it case-insensitive.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Post by Jonah Bron »

Duh!

*smacks forehead in utter disbelief of own stupidity*

:drunk:
Post Reply