php 使用PHP语言在URL中用破折号替换所有空格和特殊符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2627523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all spaces and special symbols with dash in URL using PHP language
提问by khushbu
How to replace spaces and dashes when they appear together with only dash in PHP?
当空格和破折号与 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.
在此我想用 PHP 中的破折号替换所有特殊字符。在 URL 中,“阳台”后面已经有一个破折号。如果我用特殊字符替换破折号,那么它会变成两个破折号,因为 URL 中已经有一个破折号,而我只想要 1 个破折号。
回答by Your Common Sense
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);
回答by codaddict
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:
如果连字符周围最多可以有一个空格,您可以使用John的答案。如果可能有多个空格,您可以尝试使用preg_replace:
$str = preg_replace('/\s*-\s*/','-',$str);
This would replace even a -not surrounded with any spaces with -!!
这甚至会-用-!!替换没有被任何空格包围的a
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.
现在这将确保 a-在被替换时至少有一个空间围绕它。
回答by Tali Luvhengo
This should do it for you
这应该为你做
strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
回答by sushilprj
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.
应用此正则表达式/[^a-zA-Z0-9]/, '-',它将替换所有非字母数字字符-。将它存储在一个变量中并再次应用这个正则表达式 /\-$/, '',它将转义最后一个字符。
回答by saqibahmad
Its old tread but to help some one, Use this Function:
它的旧胎面但为了帮助某人,请使用此功能:
function urlSafeString($str)
{
$str = eregi_replace("[^a-z0-90]","",str_replace("-"," ",$str));
$str = eregi_replace("[0]+","-",trim($str));
return $str;
}
it will return you a url safe string
它会返回一个 url 安全字符串

