PHP regex在每个空行之后用第二行替换第一行


PHP regex to replace 1st line with 2nd line after every empty line

是否可以使用PHP preg_replace来获取每行的值并将其替换为下一行的值?例如:

id "text 1"
str ""
id "text 2"
str ""
id "text 6"
id_p "text 6-2"
str[0] ""
str[1] ""

搜索结果

id "text 1"
str "text 1"
id "text 2"
str "text 2"
id "text 6"
id_p "text 6-2"
str[0] "text 6"
str[1] "text 6-2"

我使用正则表达式,但我不能这样做,我不确定它是否可能或不仅与正则表达式。

用以下正则表达式匹配捕获idid_p中的值的块:

'~^id'h+"(.*)"(?:'Rid_p'h+"(.*)")?(?:'Rstr(?:'['d])?'h*"")+$~m'

将这些块传递给preg_replace_callback回调方法,并将str ""str[1] ""替换为第一个捕获组值,将str[1] ""替换为第二个捕获组值。

使用

$re = '~^id'h+"(.*)"(?:'Rid_p'h+"(.*)")?(?:'Rstr(?:'['d])?'h*"")+$~m'; 
$str = "id '"text 1'"'nstr '"'"'n'nid '"text 2'"'nstr '"'"'n'nid '"text 3'"'nstr '"'"'n'nid '"text 4'"'nstr '"'"'n'nid '"text 5'"'nstr '"'"'n'nid '"text 6'"'nid_p '"text 6-2'"'nstr[0] '"'"'nstr[1] '"'""; 
$result = preg_replace_callback($re, function($m){
    $loc = $m[0];
    if (isset($m[2])) {
        $loc = str_replace('str[1] ""','str[1] "' . $m[2] . '"', $loc);
    }
    return preg_replace('~^(str(?:'[0])?'h+)""~m', "$1'"$m[1]'"",$loc);
}, $str);
echo $result;

查看这个PHP演示

既然结构总是相同的,为什么要用正则表达式呢?一个简单的循环就可以做到这一点:

$ar[] = 'id "text 1"';
$ar[] = 'str ""';
$ar[] = '';
$ar[] = 'id "text 2"';
$ar[] = 'str ""';
$ar[] = '';
for($i=0;$i<count($ar);$i++){
    if($i%3 == 0){
        $ar[($i+1)] = $ar[$i];
    }
}
print_r($ar);
// Array ( [0] => id "text 1" [1] => id "text 1" [2] => [3] => id "text 2" [4] => id "text 2" [5] => ) 

您可以尝试下面的regExp。也许它有帮助:

<?php
    $string = 'id "text 1"'nstr ""'n'nid "text 2"'nstr ""';
    $rx     = "#(['"'])*([^''"]*?)(['"'])*('n's*?'n*?)(str's)(['"'])*([^''"]*?)(['"'])*#si";
    $res = preg_replace($rx, "$1$2$3$4$5$6$2$6", $string);