0

I have one file, eg: hello.txt with the following content in it

Hi Nice

INSERT TEXT MARKER

I 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!

1
  • 1
    if there is no pattern matching then why not user str_replace? Commented Feb 27, 2014 at 3:54

2 Answers 2

1

You need the delimiter.

$new_contents = preg_replace('/'.$insert_marker.'/',  ($after) ? '$0' . $text : $text . '$0', $contents);

And it's better use preg_quote():

$new_contents = preg_replace('/'.preg_quote($insert_marker, '/').'/',  ($after) ? '$0' . $text : $text . '$0', $contents);
Sign up to request clarification or add additional context in comments.

Comments

0

Besides the fact that your regular expression is missing the delimiters, you don't actually need it in the first place; the following code will do the same thing:

file_put_contents($file_path, str_replace(
    $insert_marker, 
    $after ? $insert_marker . $text : $text . $insert_marker, 
    $contents
));

Comments

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.