PHP-删除多余的空格,但不要换行 [英] PHP - Remove excess Whitespace but not new lines
问题描述
我一直在寻找一种方法来删除字符串中多余的空格(也就是说,如果两个或两个以上的空格彼此相邻,则只保留1个空格并删除其他空格),我发现了这个
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?
推荐答案
http://www.php.net/manual/zh/regexp.reference.escape.php
定义\h
any horizontal whitespace character (since PHP 5.2.4)
所以可能您正在寻找
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 );
这篇关于PHP-删除多余的空格,但不要换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!