简体   繁体   English

使用PHP语言将所有空格和特殊符号替换为URL中的破折号

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

How to replace spaces and dashes when they appear together with only dash in PHP? 当它们与PHP中的破折号一起出现时如何替换空格和破折号?

eg 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. 在这里我想用PHP中的破折号替换所有特殊字符。 In the URL there is already one dash after "balcony". 在URL中,在“阳台”之后已经有一个破折号。 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. 如果我用特殊字符替换短划线,那么它会变成两个短划线,因为URL中已经有一个短划线,我只想要一个破折号。

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) 因为可以有其他字符,在URl中不允许(例如,+号,用作空格替换)

So, to make a valid url from a free-form text 因此,要从自由格式文本中创建有效的URL

$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 . 如果连字符周围可能有最多一个空格,您可以使用John的答案。 If there could be more than one space you can try using preg_replace : 如果可以有多个空格,您可以尝试使用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. 现在这将确保-在被替换时至少有一个空间围绕它。

这应该为你做

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 - . 应用该正则表达式/[^a-zA-Z0-9]/, '-' ,其将与替换所有的非字母数字字符- 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 它会返回一个url安全字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM