Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all spaces and special symbols with dash in URL using PHP language

Tags:

How to replace spaces and dashes when they appear together with only dash in PHP?

e.g below is my URL

http://kjd.case.150/1 BHK+Balcony- 700+ sqft. spacious apartmetn Bandra Wes 

In this I want to replace all special characters with dash in PHP. In the URL there is already one dash after "balcony". If I replace the dash with a special character, then it becomes two dashes because there's already one dash in the URL and I want only 1 dash.

like image 595
khushbu Avatar asked Apr 13 '10 06:04

khushbu


People also ask

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.

How remove all special characters 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. }


1 Answers

I'd say you may be want it other way. Not "spaces" but every non-alphanumeric character. Because there can be other characters, disallowed in the URl (+ sign, for example, which is used as a space replacement)

So, to make a valid url from a free-form text

$url = preg_replace("![^a-z0-9]+!i", "-", $url); 
like image 178
Your Common Sense Avatar answered Oct 18 '22 10:10

Your Common Sense