Replacing multiple (only internal) spaces with one in PHP?

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

A regular expression '/[ ]{2,}/'will not do the trick, because it also matches leading and trailing spaces. Until (?!\S+)\s{2,}(?!\S+) it matches all the interior spaces .

+5
source share
2 answers
$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);
+6
source
$test3 = preg_replace('/\s\s+/', ' ', $test3 );
-1
source

All Articles