删除过多的行返回 [英] Remove excessive line returns
问题描述
我正在寻找类似 trim() 的东西,但要在字符串的范围内.用户有时会在输入后输入 2、3、4 或更多行回车,我需要清理此输入.
I am looking for something like trim() but for within the bounds of a string. Users sometimes put 2, 3, 4, or more line returns after they type, I need to sanitize this input.
样本输入
i like cats
my cat is happy
i love my cat
hope you have a nice day
期望的输出
i like cats
my cat is happy
i love my cat
hope you have a nice day
我没有看到任何内置内容,并且字符串替换需要多次迭代才能完成工作.在我提出一个小的递归字符串替换之前,我想看看你们还有什么其他建议.
I am not seeing anything built in, and a string replace would take many iterations of it to do the work. Before I whip up a small recursive string replace, I wanted to see what other suggestions you all had.
我有一种奇怪的感觉,这个也有一个正则表达式.
I have an odd feeling there is a regex for this one as well.
推荐答案
终于搞定了,需要preg所以你用的是php中的PCRE版本,还需要一个\n\n替换字符串,为了不擦除除一个之外的所有行尾:
Finally managed to get it, needs preg so you are using the PCRE version in php, and also needs a \n\n replacement string, in order to not wipe all line endings but one:
$body = preg_replace("/\n\n+/", "\n\n", $body);
感谢让我走上正轨.
这篇关于删除过多的行返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!