PHP正则表达式在每个空行后用第二行替换第一行

时间:2016-09-15 08:54:21

标签: php regex preg-replace preg-replace-callback

是否可以使用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"

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

感谢任何帮助或指导。

3 个答案:

答案 0 :(得分:1)

将捕获idid_p内的值的块与this regex匹配:

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

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

使用

$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;

请参阅this PHP demo

答案 1 :(得分:0)

由于结构始终相同,为什么还要使用正则表达式呢?一个简单的循环可以做到这一点:

$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] => ) 

答案 2 :(得分:0)

您可以尝试下面的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);