我有一个应该执行以下任务的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;
我没有发现此代码有任何问题。但是在输出中显示多个胶水。但我已经在代码的第二行删除了多个空格。那为什么它会出现多个胶水?谁有任何解决方案?
答案 0 :(得分:2)
但我已经删除了代码第二行中的多个空格
不,你没有删除空格。第二行代码在$nospecial
中保留字母,数字,空格和加号(+
)。
A character class匹配主题中的单个字符。字符类中的\s+
并不意味着“一个或多个空格字符”。它表示空格字符(\s
)或加号(+
)。如果它意味着你的意思,$nospecial
将根本不包含任何空格字符。
我建议你将第二个处理步骤拆分为两个:首先删除所有特殊字符(保留字母,数字和空格),然后压缩空格(单个替换中无法同时执行这两个处理)。
然后可以在一次操作中将压实与用胶水替换空间结合起来:
// 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在评论中提出这一点,我也认为这是件好事;最有可能的是,以这种方式生成的字符串被问题的作者用作文件名。