user453089 user453089 - 7 months ago 82
PHP Question

PHP remove special character from string

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);


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

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