tags:

views:

423

answers:

4

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.

+1  A: 

Something like this:

str_replace('- ','-',$url);
zaf
+1  A: 

If there could be max one space surrounding the hyphen you can use the answer by John. If there could be more than one space you can try using preg_replace:

$str = preg_replace('/\s*-\s*/','-',$str);

This would replace even a - not surrounded with any spaces with - !!

To make it a bit more efficient you could do:

$str = preg_replace('/\s+-\s*|\s*-\s+/','-',$str);

Now this would ensure a - has at least one space surrounding it while its being replaced.

codaddict
+1  A: 

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);
Col. Shrapnel
Shouldn't those be forward slashes, rather than exclamation marks?
Eric
You've gotta slice off the domain name first, else you'll lose your dots.
Eric
+1  A: 

This should do it for you

strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));

Talifhani Luvhengo