My database contains records that have:
1) First line delimited with double \n\n and the rest delimited with \n:
Introduction
Line 1
Line 2
2) Everything delimited with \n:
Line 1
Line 2
Line 3
3) Nothing delimited:
Introduction
My goal is to add “>>” before each line that’s delimited with a single \n. The spaghetti dinner that I cooked (and it works) looks as follows:
list($intro, $details) = split("\n\n", $dbInput);
if ($details) {
$temp = split("\n", $details);
array_walk($temp, create_function('&$v,$k', '$v = ">> $v";'));
$dbOutput = "$intro \n\n ".join("\n", $temp);
} else {
$temp = split("\n", $intro);
if (count($temp) > 1) {
array_walk($temp, create_function('&$v,$k', '$v = ">> $v";'));
$dbOutput = join("\n", $temp);
} else $dbOutput = $temp[0];
}
An example of what I want to achieve:
Introduction
>> Line 1
>> Line 2
>> Line 3
or
>> Line 1
>> Line 2
>> Line 3
or
Introduction
QUESTIONS: How would I optimize this code to combine array_walk with split and join in the same statement somehow along the following lines:
$a = join("\n" , array_walk(split("\n", $a), create_function(('&$v,$k', '$v = ">> $v";')) ) );
My personal method would be to use
preg_prelaceto replace lines terminating in\n(and not\n\nwith>>at the front.My guess is you don’t want the
To have the
>>in front?In that case:
Explanation of regex:
The first bit captures
Line1andLine2, but notLine3, as this is terminated by end-of-string and not a\n. The second bit of regex capturesLine3.They also both exclude a single-line string like
Introduction.