php Replacing multiple spaces with a single space

PhpRegexFormattingString FormattingEreg Replace

Php Problem Overview


I'm trying to replace multiple spaces with a single space. When I use ereg_replace, I get an error about it being deprecated.

ereg_replace("[ \t\n\r]+", " ", $string);

Is there an identical replacement for it. I need to replace multiple " " white spaces and multiple nbsp white spaces with a single white space.

Php Solutions


Solution 1 - Php

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

> \d, \w and \s > > Shorthand character classes matching > digits, word characters (letters, > digits, and underscores), and > whitespace (spaces, tabs, and line > breaks). Can be used inside and > outside character classes.

Solution 2 - Php

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

\s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

Solution 3 - Php

preg_replace("/[[:blank:]]+/"," ",$input)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniView Question on Stackoverflow
Solution 1 - PhpcletusView Answer on Stackoverflow
Solution 2 - PhpSomnath MulukView Answer on Stackoverflow
Solution 3 - Phpghostdog74View Answer on Stackoverflow