PHP - Remove excess Whitespace but not new lines

你说的曾经没有我的故事 提交于 2019-11-29 19:05:33

问题


i was looking for a way to remove excess whitespaces from within a string (that is, if 2 or more spaces are next each other, leave only 1 and remove the others), i found this Remove excess whitespace from within a string and i wanted to use this solution:

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

but this removes new lines aswell, while i want to keep them. Is there any way to keep newlines while removing excess whitespace?


回答1:


http://www.php.net/manual/en/regexp.reference.escape.php defines \h any horizontal whitespace character (since PHP 5.2.4) so probably you are looking for

$foo = preg_replace( '/\h+/', ' ', $foo );

example: http://ideone.com/NcOiKW




回答2:


if you want to remove excess of only-spaces (not tabs, new-lines, etc) you could use HEX code to be more specific:

    $text = preg_replace('/\x20+/', ' ', $text);


来源:https://stackoverflow.com/questions/16725894/php-remove-excess-whitespace-but-not-new-lines

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