如何修剪多个换行符?
例如,$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
"
我试过这个答案,但它不工作的情况下,我认为,
$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
"
只接受单行换行。
我还想同时修剪多个空白,如果我在下面这样做,我不能保存任何换行!
$text = preg_replace('/'s's+/', ' ', trim($text));
我怎么能做到这两件事在行正则表达式?
您的换行符是'r'n
,而不是'n
:
$text = preg_replace("/('r'n){3,}/","'r'n'r'n",trim($text));
表示"每次发现3个或更多的换行符时,将它们替换为2个换行符"。
空间:
$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
不确定这是否是最好的方法,但我会使用爆炸。例如:
function remove_extra_lines($text)
{
$text1 = explode("'n", $text); //$text1 will be an array
$textfinal = "";
for ($i=0, count($text1), $i++) {
if ($text1[$i]!="") {
if ($textfinal == "") {
$textfinal .= "'n"; //adds 1 new line between each original line
}
$textfinal .= trim($text1[$i]);
}
}
return $textfinal;
}
我希望这对你有帮助。好运!