开发者

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

开发者 https://www.devze.com 2022-12-26 09:25 出处:网络
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

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 alrea开发者_运维技巧dy 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.


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);


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.


This should do it for you

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消