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.