Page 1 of 1

help using preg_replace :)

Posted: Wed Nov 18, 2009 12:58 pm
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:

Re: help using preg_replace :)

Posted: Wed Nov 18, 2009 1:36 pm
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.

Re: help using preg_replace :)

Posted: Wed Nov 18, 2009 3:28 pm
by requinix
There's also html_entity_decode...

Re: help using preg_replace :)

Posted: Wed Nov 18, 2009 3:34 pm
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

Posted: Wed Nov 18, 2009 4:07 pm
by Jonah Bron
Great. BTW, you should add A-Z to that, just in case.

Re:

Posted: Wed Nov 18, 2009 4:24 pm
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.

Posted: Wed Nov 18, 2009 4:32 pm
by Jonah Bron
Duh!

*smacks forehead in utter disbelief of own stupidity*

:drunk: