PHP 删除标点符号(无破折号)

标签 php replace character

我在 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/

相关文章:

php - 确保 MySQL 数据库中的个人数据黑客安全?

php - 这是有效的重定向语句吗?

C# 如何查找并替换字符串中的特定文本?

python - 从字符串中删除多个单词的更好方法?

oracle - 通过 CPAN Perl DBI 返回丢失/错误的字符 :Oracle ( missing umlauts)

r - 提取两个字符串之间出现的所有不同字符

在全 Angular 和半 Angular 形式之间转换 UTF8 字符串的 JavaScript 函数

javascript - 可点击的表格单元格 - 基于单元格内容的不同下拉列表

php - 在数据库中存储 session

pandas - 用先前的变量替换数据框中的 NaT