php Replacing multiple spaces with a single space

2019-01-01 10:20发布

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条回答
梦寄多情
2楼-- · 2019-01-01 10:42

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.

查看更多
回忆,回不去的记忆
3楼-- · 2019-01-01 10:58
preg_replace("/[[:blank:]]+/"," ",$input)
查看更多
无与为乐者.
4楼-- · 2019-01-01 11:01
$output = preg_replace('/\s+/', ' ',$input);

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

查看更多
登录 后发表回答