gremo
gremo

Reputation: 48487

Replacing multiple (only inner) spaces with a single one in PHP?

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

Regular expression '/[ ]{2,}/' won't do the trick because matches also leading and trailing spaces. While (?!\S+)\s{2,}(?!\S+) won't match all inner spaces.

Upvotes: 5

Views: 327

Answers (2)

chokrijobs
chokrijobs

Reputation: 761

$test3 = preg_replace('/\s\s+/', ' ', $test3 );

Upvotes: -1

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

$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);

Upvotes: 6

Related Questions