1

I currently have a file such as this.

[Line 1] Hello
[Line 2] World
[Line 3] Hello World

I wish to look for all lines containing "Hello" which would be Line 1 and 3.

Then I would like to change on that line all cases of "Line" to "Changed" so the output would be

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
  • With line two being untouched. I currently have code to locate all lines with Hello in them, but am unsure how to edit those lines alone and no other.

For example the code below does find all the lines, but also deletes everything in the process with the str_replace, so I know it's not str_replace I'm seeking.

$lines = file("lines.html");
$find = "Hello";
$repl = "Changed";
foreach($lines as $key => $line)
  if(stristr($line, $find)){$line = str_replace("$find","$repl",$line);}

2 Answers2

1

To change anything, you will have to write a new file with the existing lines and the newly changed lines. Here is a simple example

// create a new output file
$out = fopen('test2.txt', 'w');

$input = file("lines.html");
$find = "Hello";
foreach($input as $key => $line){
    $tmp = $line;
    if(stristr($line, $find)){
        $tmp = str_replace('[Line', '[Changed', $line);
        // or if `[Line` can appear more than once in the line
        //$tmp = substr_replace($line, '[Changed', 0, 5);
    }
    fwrite($out, $tmp);
}
fclose($out);

RESULT

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1

Here's a quick way if $find = "Hello"; and $repl = "Changed";:

$result = preg_replace("/\[Line (\d+\].*?$find.*)/", "[$repl $1", file("lines.html"));
file_put_contents("lines.html", $result);
  • Match [Line and capture () digits \d one or more +
  • Followed by anything .*? then the $find string then anything .* capturing all
  • Replace with [ $repl and what was captured $1
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87