本文介绍了从字符串中修剪多个换行符和多个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何修剪多个换行符?
例如
$text ="similique sunt in culpa qui officia
deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore
"
我试过这个 answer 但它不适用于上述情况我认为,
I tried with this answer but it does not work for the case above I think,
$text = preg_replace("/\n+/","\n",trim($text));
我想得到的答案是,
$text ="similique sunt in culpa qui officia
deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore
"
只接受单个换行符.
我还想同时修剪多个空白,如果我在下面这样做,我无法保存任何换行符!
Also I want to trim multiple white space at the same time, if I do this below, I can't save any line break!
$text = preg_replace('/\s\s+/', ' ', trim($text));
我怎样才能在正则表达式中做这两件事?
How can I do both thing in line regex?
推荐答案
在这种情况下,您的换行符是 \r\n
,而不是 \n
:
Your line breaks in this case are \r\n
, not \n
:
$text = preg_replace("/(\r\n){3,}/","\r\n\r\n",trim($text));
意思是每次找到 3 个或更多换行符时,用 2 个换行符替换它们".
That says "every time 3 or more line breaks are found, replace them with 2 line breaks".
空格:
$text = preg_replace("/ +/", " ", $text);
//If you want to get rid of the extra space at the start of the line:
$text = preg_replace("/^ +/", "", $text);
演示:http://codepad.org/PmDE6cDm
这篇关于从字符串中修剪多个换行符和多个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!