如何优化这个包含 SPLIT、ARRAY_WALK 和 JOIN 的 PHP 代码


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

我的数据库包含具有以下记录:

1( 第一行用双 '' 分隔,其余用 ' 分隔:

Introduction 
Line 1
Line 2

2( 用 ' 分隔的所有内容:

Line 1
Line 2
Line 3

3(无分隔:

Introduction 

我的目标是在用单个 ' 分隔的每行之前添加">>"。我做的意大利面晚餐(它有效(如下所示:

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];
}

我想要实现的示例:

Introduction
>> Line 1
>> Line 2
>> Line 3

>> Line 1
>> Line 2
>> Line 3

Introduction

问题:我将如何优化此代码以将array_walk与 split 相结合,并以某种方式加入同一语句,如下所示:

$a = join("'n" , array_walk(split("'n", $a), create_function(('&$v,$k', '$v = ">> $v";')) ) );

我个人的方法是使用preg_prelace替换以'n结尾的行(而不是'n'n前面的>>

我的猜测是你不想要

Introduction

>>在前面?

在这种情况下:

$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
*/

正则表达式的解释:

([^'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

第一个位捕获Line1Line2,但不是Line3,因为它由字符串结尾而不是'n终止。正则表达式的第二位捕获Line3

它们也都排除了单行字符串,如 Introduction .