0

I have a text file, called logs.txt, I'm trying to create a script in PHP which is supposed to check if a string which starts with foo|| exists. If it exists, it should be replaced with a specific string, otherwise a specific string will be added at the end of the file.

This is the code I tried to make:

<?php

function replaceInFile($what, $with, $file){
    $buffer = "";
    $fp = file($file);
    foreach($fp as $line){
        $buffer .= preg_replace("|".$what."[A-Za-z_.]*|", $what.$with, $line);
    }
    fclose($fp);
    echo $buffer;
    file_put_contents($file, $buffer);
}

replaceInFile("foo||", "foo||hello", "logs.txt");

?>

but it doesn't really do what I want. Can someone help me on fixing the code? Any help is appreciated.

WayneXMayersX
  • 338
  • 2
  • 10

1 Answers1

0

This should work:

$newline = preg_replace('/^' . $what . '(.*)$/', $with . '${1}', $line, 1 , $count);
$buffer .= ($count == 1) ? $newline : $line . $with;

The common Delimiters is / no | specially if you have | in your search criteria. Than you have to create a Capturing Group this is between ( and ). Now you can use this Capturing Group and in your replacement as ${ + number of the Capturing Group + }. In your case you only have one.

Webdesigner
  • 1,954
  • 1
  • 9
  • 16