【问题标题】:PHP regex to replace 1st line with 2nd line after every empty linePHP正则表达式在每个空行之后用第二行替换第一行
【发布时间】:2017-01-23 05:29:13
【问题描述】:

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

我使用正则表达式,但我无法做到这一点,我不确定它是否可能仅使用正则表达式。

感谢任何帮助或指导。

【问题讨论】:

  • 你说你正在使用正则表达式,你能分享一下吗?另外,如果str 值为空,您不只是尝试用前面的id 值填充str 值吗?
  • 是的,没错
  • 为什么要使用preg_replace
  • 你的格式是这样的吗?我的意思是 2 行,然后总是空的?
  • @PatrickMlr 我还能用什么,因为它是关于替换,我认为它是最好的。

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


【解决方案1】:

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

'~^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;

this PHP demo

【讨论】:

  • 它有效,谢谢。我扩展了它,但它没有按预期工作:regex101.com/r/pI0cP5/2 你能检查一下吗? id -> str[0] 和 id_p -> str[1]
  • 通过 1 次正则表达式是不可能的。您需要匹配块并分别处理它们。
  • here,块匹配正确吗?您需要的值是最后一个块中id_p 内的值吗?见this PHP demo
  • 我觉得我解释得不够好,请查看更新后的问题。 str[0] 的 id vale 和 str[1] 的 id_p
  • 我很感激,太棒了
【解决方案2】:

既然结构总是一样的,为什么还要使用正则表达式呢?一个简单的循环就可以解决问题:

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

【讨论】:

    【解决方案3】:

    你可以试试下面的正则表达式。也许有帮助:

    <?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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 2014-04-26
      相关资源
      最近更新 更多