I have one file, eg: hello.txt with the following content in it
Hi Nice
INSERT TEXT MARKERI want to create a script that enters "Hello World" after ####INSERT TEXT MARKER####.
I have used below code to do it.
<?php
function insert_into_file($file_path, $insert_marker, $text, $after = true) {
$contents = file_get_contents($file_path);
$new_contents = preg_replace($insert_marker, ($after) ? '$0' . $text : $text . '$0', $contents);
return file_put_contents($file_path, $new_contents);
}
$file_path = "hello.txt";
$insert_marker = "####INSERT TEXT MARKER####";
$text = "Hello World";
$num_bytes = insert_into_file($file_path,$insert_marker,$text,true);
if ($num_bytes === false) {
echo "Could not insert into file $file_path.";
} else {
echo "Insert successful!";
}
?>
But my file goes empty. Please help!
str_replace?