PHP 正则表达式:无法将 space 转换为胶水

PHP Regular Expression: could not convert space into glue

我有一个 PHP 函数应该执行以下任务: 该函数将采用 2 个参数 - 字符串和胶水(默认为“-”)。 对于给定的字符串,
-- 删除任何特殊字符
-- 小写
-- 删除多个空格
-- 用胶水 (-) 替换空格。

函数以$input为参数。我为此使用的代码如下:

         //make all the charecters in lowercase
         $low = strtolower($input);

         //remove special charecters and multiple spaces
         $nospecial = preg_replace('/[^a-zA-Z0-9\s+]/', '', $low);

         //replace the spaces into glues (-). here is the problem.
         $converted = preg_replace('/\s/', '-', $nospecial);


         return $converted;

我没有发现这段代码有什么问题。但在输出中显示了多个胶水。但我已经删除了代码第二行中的多个空格。那么为什么它显示多个胶水?谁能有什么解决办法?

but i have already removed multiple spaces in the second line of the code

不,您还没有删除 space。第二行代码在 $nospecial 中保留字母、数字、space 和加号 (+)。

A character class 匹配主题中的单个字符。字符 class 中的 \s+ 并不意味着 "one or many space characters"。它表示 space 字符 (\s) 或加号 (+)。如果这意味着你的意思,$nospecial 根本不会包含任何 space 字符。

我建议你将第二个处理步骤一分为二:首先删除所有特殊字符(保留字母,数字和spaces)然后压缩spaces(没有办法在一次替换中完成这两个操作)。

然后可以在一次操作中将压缩与用胶水替换 space 相结合:

 // Make all the charecters lowercase
 // Trim the white spaces first to avoid the final result have stray hyphens on the sides
 $low = strtolower(trim($input));

 // Remove special characters (keep letters, digits and spaces)
 $nospecial = preg_replace('/[^a-z0-9\s]/', '', $low);

 // Compact the spaces and replace them with the glue
 $converted = preg_replace('/\s+/', '-', $nospecial);

 return $converted;

更新: 添加了在任何处理之前修剪输入字符串以避免得到以胶水开始或结束的结果。这不是问题所要求的,这是@niet-the-dark-absol在评论中提出的,我也认为这是一件好事;问题的作者很可能将以这种方式生成的字符串用作文件名。