5
$test1 = ' surrounding1 ';               // No replace 
$test2 = '  surrounding2    ';           // No replace
$test3 = '  extra    spaces  between  '; // Becomes '  extra spaces between  '

正则表达式'/[ ]{2,}/'无法解决问题,因为匹配前导和尾随空格。虽然(?!\S+)\s{2,}(?!\S+) 不会匹配所有内部空间

4

2 回答 2

6
$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);
于 2012-09-28T10:33:58.313 回答
-1
$test3 = preg_replace('/\s\s+/', ' ', $test3 );
于 2012-09-28T10:34:54.577 回答