如何删除后跟空格的换行符?

时间:2015-07-28 21:34:32

标签: php regex preg-replace str-replace

我想删除所有换行后跟空格或换句话说;将以空格开头的所有行移动到最后一行的末尾。

示例:

$str_before = "Lorem Ipsum is simply dummy text
 of the printing and typesetting industry. 
Lorem Ipsum has been the industry's 
standard dummy text ever since the"; 

通缉结果:

$str_after = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's 
standard dummy text ever since the";

我试过这个没有成功:

$str_after = str_replace("\n"." "," ", $str_before)

如何使用php / regex实现此目的?

2 个答案:

答案 0 :(得分:2)

不是很优雅,但这应该有效。

<?php

$str = 'Lorem Ipsum is simply dummy text
 of the printing and typesetting industry. 
Lorem Ipsum has been the industry\'s 
standard dummy text ever since the';

$newStr = []; $i = 0;
foreach(preg_split("/((\r?\n)|(\r\n?))/", $str) as $line) {
  $i++;

  if ($line[0] == chr(32)) {
    $newStr[$i-1] .= $line;
  } else {
    $newStr[$i] = $line;
  }
} 
echo implode(PHP_EOL, $newStr);

答案 1 :(得分:2)

使用以下正则表达式:

^([^\n]*)\n( [^\n]*)$
Demo here

查找匹配的文件中的所有内容。替换为连接在一起的第一个和第二个捕获组。