我遇到了 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/