Replacing multiple spaces with a single space simple single line of php code:

$output = preg_replace(‘/\s+/’, ‘ ‘, $input);

This mean that spaces, tabs or line breaks (one or more) will be replaced by a single space.

Replace multiple spaces with one space:

$output = preg_replace(‘/\s+/’, ‘ ‘, $input);

Replace one or multiple tabs with one space:

$output = preg_replace(‘/\t+/’, ‘ ‘, $input);

Replace one or multiple new lines with one space:

$output = preg_replace(‘/\n\r+/’, ‘ ‘, $input);


Find more about regular expressions at


\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks).

PHP remove multiple whitespaces
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *