ChatGPT解决这个技术问题 Extra ChatGPT

php Replacing multiple spaces with a single space [duplicate]

This question already has answers here: How can I convert ereg expressions to preg in PHP? (4 answers) Closed 3 years ago.

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.


c
cletus

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: 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: by chance, a moment ago i benchmarked those on real-life data, result (for calls on ~8300 various text articles): /(?:\s\s+|\n|\t)/ => 1410 (slowest), /\s+/ => 611 (ok'ish), /\s\s+/ => 496 (fastest). The last one does not replace single \n or \t, but thats ok for my case.
/\s{2,}/u' - if you have some UTF-8 problem add /u switch
for unicode there is mb_ereg_replace doc
@cletus , great work!, with keeping this regex pattern, is there a way to get rid of all spaces at the right & and the left of the string? for example, " a b c ", would be "a b c", I know we could use trim($output), but it would be nice to have it in regex
H
HoldOffHunger
$output = preg_replace('/\s+/', ' ',$input);

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


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

Doesn't replace "\n" (PHP 5.3), "/\s+/" get's job done. ;)
Actually this helped, \s messed up my multibyte word, replaceing Š with some kind of square.
@MārtiņšBriedis There is separate multibyte function: php.net/manual/en/function.mb-ereg-replace.php
Unlike other answers, this command only replaces spaces (not newlines, etc...), which is exactly what is needed! Thank you so much!