我在 stackoverflow 上找到了下面的脚本,它用破折号替换了特殊字符,以实现干净的 url 构建。但是,它做得不好,因为它将标点符号替换为破折号,如下面的“坏”示例所示。所以,相反,我希望特别标点符号不要被任何东西替换,而只是被删除……没有空格,没有破折号。对此的任何帮助将不胜感激。
例子:
today's weather is hot!
good:
todays-weather-is-hot
bad:
today-s-weather-is-hot-
This script does the bad example... how to make it do the good?:
function slugUrl($string) {
$string = strtolower($string);
$string = preg_replace('/[^a-zA-Z0-9]/i','-',$string);
$string = preg_replace("/(-){2,}/",'$1',$string);
return $string;
}
最佳答案
这个呢? (我只是先去掉了标点符号)
function slugUrl($string){
$string = strtolower($string);
$string = preg_replace('/[!?\']/','',$string);
$string = preg_replace('/[^a-zA-Z0-9]/i','-',$string);
$string = preg_replace("/(-){2,}/",'$1',$string);
return $string;
}
关于PHP 删除标点符号(无破折号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092208/