简体   繁体   中英

How to optimize this PHP code that includes SPLIT, ARRAY_WALK and JOIN?

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_prelace to replace lines terminating in \\n (and not \\n\\n with >> at the front.

My guess is you don't want the

Introduction

To have the >> in front?

In that case:

$pattern = '/([^\n]+)(?=\n(?!\n))|(?<=(?<!\n)\n)([^\n]+)/';
$replacement = '>>$1$2';
$subject = 'Introduction 

Line 1
Line 2
Line 3';

echo preg_replace ($pattern, $replacement, $subject);

/* echoes:
Introduction

>>Line 1
>>Line 2
>>Line 3
*/

Explanation of regex:

([^\n]+)(?=\n(?!\n))   # match a line followed by \n but not a \n\n
|                      # OR
(?<=(?<!\n)\n)([^\n]+) # match a line preceded by \n but not a \n\n

The first bit captures Line1 and Line2 , but not Line3 , as this is terminated by end-of-string and not a \\n . The second bit of regex captures Line3 .

They also both exclude a single-line string like Introduction .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM