php - 从字符串中删除所有特殊字符

标签 php regex url slug

我遇到了 URL 的问题,我希望能够转换可能包含任何内容的标题,并将它们剥离所有特殊字符,以便它们只有字母和数字,当然我想用连字符替换空格。

如何做到这一点?我听说过很多关于正则表达式 (regex) 的使用...

最佳答案

这应该可以满足您的需求:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

用法:

echo clean('a|"bc!@£de^&$f g');

将输出:abcdef -g

编辑:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

关于php - 从字符串中删除所有特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114411/

相关文章:

java - 在 java 中获取 URL 参数并从该 URL 中提取特定文本

javascript - 通过 Ajax 通过变量将多个变量传递给 PHP 不起作用

php - 使用 AJAX 传递表单条目以查询传递并更新到 div 标签的数据库

php - 开发 WordPress 管理链接重定向到实时站点

php - 如何使用全宽图像作为内容和页脚之间的边框

php - 使用Excel在PHP应用程序中做核心分析?

java - 正则表达式获取冒号之前和之后的字符串

c# - 在另一个正则表达式匹配后匹配所有字符的正则表达式

ruby - 如何读取一个文件的内容,然后将内容拆分成几个文件?

android - 自定义 URL 方案 Android