简体   繁体   English

如何优化包含SPLIT,ARRAY_WALK和JOIN的PHP代码?

[英]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: 1)第一行用double \\ n \\ n分隔,其余用\\ n分隔:

Introduction 

Line 1
Line 2

2) Everything delimited with \\n: 2)用\\ n分隔的所有内容:

Line 1
Line 2
Line 3

3) Nothing delimited: 3)没有任何划界:

Introduction 

My goal is to add ">>" before each line that's delimited with a single \\n. 我的目标是在用单个\\ 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: 问题:如何优化此代码以将array_walk与split组合在一起并以相应的方式连接到以下行:

$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. 我个人的方法是使用preg_prelace来替换终止于\\n (而不是\\n\\n ,前面是>>

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 . 第一位捕获Line1Line2 ,但不Line3 ,因为它以字符串结尾而不是\\n The second bit of regex captures Line3 . 正则表达式的第二位捕获Line3

They also both exclude a single-line string like Introduction . 它们也排除了像“ Introduction这样的单行字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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