PHP Найти значение в файле и удалить строки

111
26 ноября 2019, 13:50

Пытаюсь упростить задачу по удалению инфы из конфига. В конфиге есть записи типа -

### Лицевой счёт - №****
class "*********" { match if binary-to-ascii(**, *, ":", suffix(option agent.remote-id, *)) = "**:**:**:**:**" and binary-to-ascii(**, *, "", substring(option agent.circuit-id, *, *)) = "***" and binary-to-ascii(**, *, "", suffix(option agent.circuit-id, *)) = "**";}
pool { range ***.***.***.***; allow members of "******";}
### Лицевой счёт - №****
class "*********" { match if binary-to-ascii(**, *, ":", suffix(option agent.remote-id, *)) = "**:**:**:**:**" and binary-to-ascii(**, *, "", substring(option agent.circuit-id, *, *)) = "***" and binary-to-ascii(**, *, "", suffix(option agent.circuit-id, *)) = "**";}
pool { range ***.***.***.***; allow members of "******";}
### Лицевой счёт - №****
class "*********" { match if binary-to-ascii(**, *, ":", suffix(option agent.remote-id, *)) = "**:**:**:**:**" and binary-to-ascii(**, *, "", substring(option agent.circuit-id, *, *)) = "***" and binary-to-ascii(**, *, "", suffix(option agent.circuit-id, *)) = "**";}
pool { range ***.***.***.***; allow members of "******";}

Задача найти запись "### Лицевой счёт - №****" и удалить эту запись и 2 строчки после нее

Мой код:

$file = 'v309.conf';
$searchfor = '### Лицевой счёт - №3187';
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
   echo "Найдено:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "Записи не найдено!";
}

Как я могу это сделать?

Или, как удалить все строчки, включая искомую строку до следующей строки до "###..."

Answer 1
$file = __DIR__ . '/v309.conf';
$searchfor = '### Лицевой счёт - №3187';
$contents = file_get_contents($file);
$blocks = array_filter(preg_split('~^(?=###)~m', $contents));
$delete = preg_grep("~$searchfor\b~", $blocks);
if ($delete) {
    $new = array_diff($blocks, $delete);
    file_put_contents($file, $new);
}
Answer 2

Давайте начнем с простого и с наиболее простых вариантов. По вашему тексту видно, что та строчка которую надо удалить всегда начинается с ### Лицевой счёт - №, этого достаточно, можно обойтись без регулярок:

$contents = '### Лицевой счёт - №****
class "*********" { match if binary-to-ascii(**, *, ":", suffix(option agent.remote-id, *)) = "**:**:**:**:**" and binary-to-ascii(**, *, "", substring(option agent.circuit-id, *, *)) = "***" and binary-to-ascii(**, *, "", suffix(option agent.circuit-id, *)) = "**";}
pool { range ***.***.***.***; allow members of "******";}
### Лицевой счёт - №****
class "*********" { match if binary-to-ascii(**, *, ":", suffix(option agent.remote-id, *)) = "**:**:**:**:**" and binary-to-ascii(**, *, "", substring(option agent.circuit-id, *, *)) = "***" and binary-to-ascii(**, *, "", suffix(option agent.circuit-id, *)) = "**";}
pool { range ***.***.***.***; allow members of "******";}
### Лицевой счёт - №****
class "*********" { match if binary-to-ascii(**, *, ":", suffix(option agent.remote-id, *)) = "**:**:**:**:**" and binary-to-ascii(**, *, "", substring(option agent.circuit-id, *, *)) = "***" and binary-to-ascii(**, *, "", suffix(option agent.circuit-id, *)) = "**";}
pool { range ***.***.***.***; allow members of "******";}';
$new_contents = '';
$count = -1;
$contents = explode(PHP_EOL, $contents);
foreach ($contents as $key => $value) {
    if (mb_substr($value, 0, 20) == '### Лицевой счёт - №') {
        $count = 0;
    }
    if ($count == -1) {
        $new_contents[] = $value;
    } else {
        $count++;
        if ($count == 3) { // сколько строчек суммарно удаляем
            $count = -1;
        }
    }
}
$new_contents = implode(PHP_EOL, $new_contents);
var_dump($new_contents);
READ ALSO
Как убрать ссылки из php виджета

Как убрать ссылки из php виджета

Вот код php виджетаВ виджете все добавленные картинки становятся со ссылками, подскажите, пожалуйста, как убрать автоматические ссылки? Конечно...

90
Генерация PHP-классов из русскоязычной XSD

Генерация PHP-классов из русскоязычной XSD

Есть XSD, которая в качестве значений аттрибутов использует русскоязычные наименованияНапример,

97
возможные комбинации массива php

возможные комбинации массива php

Есть массив $test = ['a','b','c','d'];

94
Как в jQuery высчитать процент

Как в jQuery высчитать процент

Есть фрагмент кода для wp woocommerce:

98