【问题标题】:Remove multiple whitespaces - PHP doesn't find the spaces删除多个空格 - PHP 找不到空格
【发布时间】:2014-09-21 16:34:13
【问题描述】:

我知道,有很多类似的问题,你会说,是重复的,但我找不到解决方案! 我需要删除多个空格,只写一个空格。在我的代码中,我写了'REPLACE'而不是'',只是为了澄清。这是一些我已经测试过但无法正常工作的代码:

$string=$data['post_content'];
$filtered1=preg_replace("/[^\S\r\n]+/",'REPLACE',$string);
$filtered2=preg_replace("#[^\S\r\n]+#",'REPLACE',$string);
$filtered3=preg_replace("#[^\S\r\n][^\S\r\n]+#",'REPLACE',$string);
$filtered4=preg_replace('#[^\S\r\n][^\S\r\n]+#','REPLACE',$string);
$filtered5=preg_replace('#!\s+!#', 'REPLACE', $string);
$filtered6=preg_replace("/(?<=\s)\x20|\x20(?=\s)/", "REPLACE", $string);
$filtered7=preg_replace("/([\s])\1+/", "REPLACE", $string);
$filtered8=preg_replace("#[^\S\r\n][^\S\r\n]#",'REPLACE',$string);
$filtered9=preg_replace("'/\s+/'",'REPLACE',$string);
$testing1=str_replace("  ","REPLACE",$string);
$testing2=str_replace("\s",'REPLACE',$string);
$testing3=str_replace(array('  '),'REPLACE',$string);
$testing4=str_replace('  ',"REPLACE",$string);
$testing5=str_replace("  ","REPLACE",$string);
$testing6=str_replace(array("  "),'REPLACE',$string);
$testing7=str_replace(array("\s\s"),'REPLACE',$string);

这是字符串测试:

这是一个测试 1   2   3     4     6      结束

结果是$filtered1$filtered2

这个REPLACEisREPLACEaREPLACEtestREPLACE1  REPLACE2  REPLACE3    REPLACE4    REPLACE6     REPLACE结束。

对于所有其他人,结果是:

这是一个测试 1   2   3     4     6      结束

就像 PHP 没有找到空格,即使 explode 没有找到双空格“”。我正在使用 PHP 5.5.1

【问题讨论】:

  • 如果您想删除所有多个空格,您可以使用preg_replace('/\s+/',' ', $string);(将所有 1 个或多个空格实例替换为单个空格)
  • 仍然返回相同的结果:“这是一个测试 1 2 3 4 6 结束”
  • 您的预期输出是什么?并且您想精确匹配 2 个可以使用的空格 preg_replace('/\s{2}/',' ', $string);
  • 出于某种奇怪的原因,在 cmets 中结果看起来不错。应该是这样的

标签: php regex str-replace


【解决方案1】:

来了 使用

preg_replace('/[^\S\r\n]{2,}/',' ',$string); 将双空格转换为单空格

在这里查看演示:http://regex101.com/r/sP7wH7/1

但我宁愿使用最简单的preg_replace('/ {2,}/',' ',$string); 来完成这个

【讨论】:

  • 我知道正则表达式应该可以工作,但仍然返回相同的结果:这是一个测试 1 2 3 4 6 结束
【解决方案2】:

您的测试字符串有不间断的空格,\s 在您的正则表达式模式中不会拾取这些空格。改用这个:

preg_replace('/(\s+)|(\xA0+)/u', ' ', $string);

【讨论】:

  • 我需要保留换行符,但您的回答对于了解修饰符“u”很有用
【解决方案3】:

问题不在于 RegEx,问题在于修饰符,感谢 Aurimas 的回答,我使用了修饰符 u。以下是可能的解决方案:

$filtered1=preg_replace("/[^\S\r\n]+/u",' ',$string);
$filtered2=preg_replace("#[^\S\r\n]+#u",' ',$string);
$filtered3=preg_replace("#[^\S\r\n][^\S\r\n]+#u",' ',$string);
$filtered10=preg_replace('/[^\S\r\n]{2,}/u',' ',$string);0
$filtered11=preg_replace('/\h+/u', ' ', $string);
$filtered16=preg_replace('/(\xA0+)/u', ' ', $string);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2014-02-18
    相关资源
    最近更新 更多