【问题标题】:PHP Regular Expression: could not convert space into gluePHP正则表达式:无法将空格转换为胶水
【发布时间】:2016-01-11 16:03:18
【问题描述】:

我有一个 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;

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

【问题讨论】:

  • 对不起...它不起作用.. :(

标签: php regex preg-replace whitespace


【解决方案1】:

但我已经在代码的第二行中删除了多个空格

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

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 在评论中建议,我也认为这是一件好事;最有可能的是,以这种方式生成的字符串被问题的作者用作文件名。

【讨论】:

  • 考虑添加 trim($converted,'-') 以删除两侧的任何杂散连字符。
  • 你犯了@HamZA在他的评论中犯的同样的错误。从第一个正则表达式中删除 \s 后,将在该步骤中删除所有空格。
  • 嘿...您的代码运行良好...我已经更改了您的代码的一小部分。我在代码的第二行添加了一个“s”,如下所示: $nospecial = preg_replace('/[^a-zA-Z0-9\s]/', '', $low);现在它可以正常工作了。谢谢 :) @axiac
  • 我的话说了些什么,但我的代码却说反了。我的坏:-)
  • @HamZa 感谢您将\s 添加到正则表达式中。删除A-Z 也是有道理的;该字符串在前一个语句中被转换为小写。也许我该睡觉了,以免我的答案误导他人:-)
猜你喜欢
  • 2016-04-02
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多