Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 900
user453089 Avatar asked May 20 '11 14:05

user453089


People also ask

How remove all special characters from a string in PHP?

Using str_ireplace() Method: The str_ireplace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).

How do I remove numbers and special characters from a string in PHP?

1 Answer. Show activity on this post. function clean($string) { $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. return preg_replace('/[^A-Za-z\-]/', '', $string); // Removes special chars. }


1 Answers

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

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String); 
like image 148
Luke Sneeringer Avatar answered Sep 30 '22 08:09

Luke Sneeringer