Reputation: 251
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.
Upvotes: 25
Views: 44073
Reputation: 962
Its old tread but to help some one, Use this Function:
function urlSafeString($str)
{
$str = eregi_replace("[^a-z0-9\040]","",str_replace("-"," ",$str));
$str = eregi_replace("[\040]+","-",trim($str));
return $str;
}
it will return you a url safe string
Upvotes: -1
Reputation: 359
This should do it for you
strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
Upvotes: 2
Reputation: 2243
Apply this regular expression /[^a-zA-Z0-9]/, '-'
which will replace all non alphanumeric characters with -
. Store it in a variable and again apply this regular expression /\-$/, ''
which will escape the last character.
Upvotes: 1
Reputation: 157864
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);
Upvotes: 50
Reputation: 455020
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.
Upvotes: 2