php Replacing multiple spaces with a single space [duplicate]

时光怂恿深爱的人放手 提交于 2019-11-26 03:04:29

问题


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.


回答1:


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.




回答2:


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

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




回答3:


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


来源:https://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!