PHP-删除多余的空格,但不要换行 [英] PHP - Remove excess Whitespace but not new lines

查看:161
本文介绍了PHP-删除多余的空格,但不要换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法来删除字符串中多余的空格(也就是说,如果两个或两个以上的空格彼此相邻,则只保留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 );

示例: http://ideone.com/NcOiKW

这篇关于PHP-删除多余的空格,但不要换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆