How to Remove Multiple Whitespaces in PHP

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

http://www.regular-expressions.info/reference.html

Examples:

\d, \w and \s

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


<?php
$str = "This is  a string       with
spaces, tabs and newlines present";

$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);

echo $str;
echo "\n---\n";
echo "$stripped";
?>

$ro = preg_replace('/\s+/', ' ', $row['message']);

 

https://escapequotes.net/php-remove-multiple-whitespaces/