vendredi 29 novembre 2019

How can I replace a block of code in a php file using preg_replace and regex expression?

I have a php config file that contains a few arrays use to store settings.

<?php
$array1 = array(
    "item1' => "value1",
    "item2' => "value2",
    "item3' => "value3",
    "item4' => "value4",
);
$array2 = array(
    "item1"
    "item2"
    "item3"
    "item4"
);
$array3 = array(
    "item1' => "value1",
    "item2' => "value2",
    "item3' => "value3",
    "item4' => "value4",
);
?>

I am not very good with regex expression (yet).I am having diffulties understanding how it works. I am trying to build a regex expression that would allow me to replace all lines in array2. Using preg_replace($pattern, $replacement, $str).

$str=file_get_contents('config.php');
$pattern = 'some regex';
$replacement = '    "itemA",
    "itemB",
    "itemC",
    "itemD",';
$str=preg_replace($pattern, $replacement, $str);
file_put_contents('config.php', $str);

Aucun commentaire:

Enregistrer un commentaire