Skip to content
Advertisement

Replace line breaks not followed by a date in PHP [closed]

I try to parse a string using PHP line by line. Usually each data set consists of 13 values separated by tabs. One of those values contains comments and those might have a line break in it (which I cannot avoid – data is imported). If it does I cannot loop through my lines anymore because one dataset does not consist of 13 values anymore and they are split across two lines.

Each new line usually starts with a date like 30.12.2020

How can I check if there are line brakes within my string which are not followed by a date and delete them?

Example string:

$input = “30.12.2020 Line 1n30.12.2020 Line 2nLine 3n30.12.2020Line 4”;

Line 2 and Line 3 should in this case be printed on the same line.

Advertisement

Answer

You could do a regex replacement on the following pattern:

r?n(?!d{2}.d{2}.d{4})

Sample script:

$input = "Line 1n30.12.2020 Line 2nLine 3n30.12.2020Line 4";
$output = preg_replace("/r?n(?!d{2}.d{2}.d{4})/", "", $input);
echo $input . "nn" . $output;

This prints:

Line 1
30.12.2020 Line 2
Line 3
30.12.2020Line 4

Line 1
30.12.2020 Line 2Line 3
30.12.2020Line 4
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement