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);}
6
  • Does stackoverflow.com/questions/8163746/… contain any useful information? Commented May 28, 2020 at 15:33
  • What about cases where the string contains "Hello" but doesn't lead with it? e.g. [Line 4] He Said Hello Commented May 28, 2020 at 15:38
  • 1
    Anything you tried already? Commented May 28, 2020 at 15:38
  • 1
    What do you mean by "the troubled area"? What have you tried so far? If you have identified which lines to change, why not run a simple string replacement on these lines? Commented May 28, 2020 at 15:59
  • Did you give up? Commented Jun 3, 2020 at 18:30

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@Scoots Added an alternative if that is an issue to the OP :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.