Php remove spaces and special characters from string
UpdateThe solution below has a "SEO friendlier" version: Show
The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs. After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one]
reported that, say, converting "Viaggi Economy Perù" to There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck. In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. Previous answerA simple approach:
Note that you might have to first So the finished function along with test cases:
To handle UTF-8 I used a The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out. How remove all special characters and spaces from a string in PHP?This should do what you're looking for: function clean($string) { $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. }
How do I remove special characters and spaces from a string?In the following example, the removeAll() method removes all the special characters from the string and puts a space in place of them.. public class RemoveSpecialCharacterExample1.. public static void main(String args[]). String str= "This#string%contains^special*characters&.";. str = str.replaceAll("[^a-zA-Z0-9]", " ");. How can I replace special characters in a string in PHP?The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
What is the use of Htmlspecialchars in PHP?The htmlspecialchars() function converts some predefined characters to HTML entities.
|