PHP remove special character from string

user453089 picture user453089 · May 20, 2011 · Viewed 161.2k times · Source

I have problems with removing special characters. I want to remove all special characters except "( ) / . % - &", because I'm setting that string as a title.

I edited code from the original (look below):

preg_replace('/[^a-zA-Z0-9_ -%][().][\/]/s', '', $String);

But this is not working to remove special characters like: "’s, "“", "â€", among others.

original code: (this works but it removes these characters: "( ) / . % - &")

preg_replace('/[^a-zA-Z0-9_ -]/s', '', $String);

Answer

Luke Sneeringer picture Luke Sneeringer · May 20, 2011

Your dot is matching all characters. Escape it (and the other special characters), like this:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);