【问题标题】:Replacing multiple (only inner) spaces with a single one in PHP?在 PHP 中用一个空格替换多个(仅内部)空格?
【发布时间】:2012-09-28 10:27:52
【问题描述】:
$test1 = ' surrounding1 ';               // No replace 
$test2 = '  surrounding2    ';           // No replace
$test3 = '  extra    spaces  between  '; // Becomes '  extra spaces between  '

正则表达式'/[ ]{2,}/' 不会起作用,因为它还匹配前导和尾随空格。而(?!\S+)\s{2,}(?!\S+)won't match all inner spaces

【问题讨论】:

  • 我已经编辑了您的第三个示例,以使其符合您在问题中所写的内容。我希望你同意这个修改。
  • @TimPietzcker 是的,谢谢。我会研究你的答案并尽快接受。

标签: php regex preg-replace pcre


【解决方案1】:
$result = preg_replace(
    '/(?<!   # Assert that it is impossible to match...
     ^       #  start-of-string
    |        #  or
     [ ]     #  a space
    )        # ...before the current position.
    [ ]{2,}  # Match at least 2 spaces.
    (?!      # Assert that it is impossible to match...
     [ ]     #  a space
    |        #  or
     $       #  end-of-string
    )        # ...after the current position./x', 
    ' ', $subject);

【讨论】:

  • @Gremo:我把它变成了一个冗长的正则表达式,希望现在更清楚了。
  • @YogeshSuthar:是的,不应该。格雷莫只想浓缩内部空间。
【解决方案2】:
$test3 = preg_replace('/\s\s+/', ' ', $test3 );

【讨论】:

  • 这匹配前导和尾随空格。
  • 不,你的意思是 trim() 但这会从字符串中去除多余的空格。
猜你喜欢
  • 2013-07-03
  • 2013-11-25
  • 2012-06-04
  • 2013-05-30
  • 2013-10-31
  • 2010-11-19
  • 1970-01-01
  • 2017-03-08
相关资源
最近更新 更多