首页 >后端开发 >php教程 >如何使用正则表达式删除非字母数字字符并用连字符替换空格?

如何使用正则表达式删除非字母数字字符并用连字符替换空格?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-23 22:05:29815浏览

How to Strip Non-Alphanumeric Characters and Replace Spaces with Hyphens Using Regular Expressions?

剥离非字母数字字符并用连字符替换空格

问题:用户在将标题转换为 URL 时面临挑战仅包含字母、数字和连字符。他们寻求一种方法来去除特殊字符并用连字符替换空格。

解决方案:正则表达式(Regex)

正则表达式是模式匹配和字符串的强大工具操纵。它们可用于实现所需的转换。

代码:

<code class="php">function clean($string) {
    // Replace spaces with hyphens
    $string = str_replace(' ', '-', $string);
    
    // Remove non-alphanumeric characters and hyphens
    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
    
    // Replace multiple hyphens with a single one
    $string = preg_replace('/-+/', '-', $string);
    
    return $string;
}</code>

用法:

<code class="php">echo clean('a|"bc!@£de^&amp;$f g');</code>

输出:

abcdef-g

其他修改:

为了防止多个连字符连续出现,请替换最后一行clean 函数的:

<code class="php">return preg_replace('/-+/', '-', $string);</code>

以上是如何使用正则表达式删除非字母数字字符并用连字符替换空格?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn