0

I want to remove all line breaks followed by a whitespace or in other words; move all lines that starts with a whitespace to the end of the last line.

Example:

$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"; 

Wanted result:

$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";

I have tried this with no success:

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

How do I achieve this using php/regex?

Henning Hall
  • 1,071
  • 1
  • 9
  • 26

2 Answers2

2

Not very elegant but this should work.

<?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);
ficuscr
  • 6,634
  • 2
  • 28
  • 47
  • 2
    (Instead of the `\r` and `\n` combinations, one could often use `\R`, which [covers most linebreak variations](http://stackoverflow.com/questions/18988536/php-regex-how-to-match-r-and-n-without-using-r-n).) – mario Jul 28 '15 at 22:41
2

Use the following regex:

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

Find everything in the file that matches. Replace with the first and second capturing group concatenated together.

James Buck
  • 1,565
  • 6
  • 13