$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。
答案 0 :(得分: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);
答案 1 :(得分:-1)
$test3 = preg_replace('/\s\s+/', ' ', $test3 );