tags:

views:

474

answers:

3

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.

+3  A: 

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.

cletus
@Cletus: This one would replace a single space with space. Don't you think something like: preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x) will be more *efficient* especially on text with several single spaces ?
codaddict
+2  A: 
preg_replace("/[[:blank:]]+/"," ",$input)
ghostdog74
Simple and does the job!
Nirmal
A: 

Great tip, thanks guys.