user1270150
user1270150

Reputation: 53

Remove multiple lines from file using PHP

I have been searching for a number of hours now for a solution to remove a block of text within a file using PHP script.

There appears to be a number of options for removing lines of text, but not a block of text. I have attempted to use preg_replace ("/^$start.*?$end/s", $replace, $fdata) with the following, but have not found a solution that works.

I am sure that someone has done this already, so any help would be much appreciated.

$start = "# Copyright 2000-";
$end = "Agreement.";

# This software product may only be used strictly in accordance
# with the applicable written License Agreement.

Upvotes: 1

Views: 838

Answers (1)

nickb
nickb

Reputation: 59699

You need multi-line mode (/m), otherwise your regex won't capture across multiple lines. Also, you should escape your regex parameters with preg_quote(), otherwise you may get undesired results (for example, in $end, it has a dot, which is a regex metacharacter, when you want it to match a single period.)

$regex = "/^" . preg_quote( $start, '/') .".*?". preg_quote( $end, '/') . "/sm";
preg_replace ( $regex, $replace, $fdata);

Upvotes: 5

Related Questions