Created
February 4, 2016 16:03
-
-
Save acacha/8b6e78b25468a4a672a8 to your computer and use it in GitHub Desktop.
Php insert text into file at marker taken from http://www.learncomputer.com/php-insert-text-into-file-at-position/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Insert arbitrary text into any place inside a text file | |
* | |
* @param string $file_path - absolute path to the file | |
* @param string $insert_marker - a marker inside the file to | |
* look for as a pattern match | |
* @param string $text - text to be inserted | |
* @param boolean $after - whether to insert text after (true) | |
* or before (false) the marker. By default, the text is | |
* inserted after the marker. | |
* @return integer - the number of bytes written to the file | |
*/ | |
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 = "/var/www/myapp/my_file"; | |
$insert_marker = "#### INSERT TEXT MARKER ####"; | |
$text = "\nI am a PHP inserted text!!!"; | |
$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!"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment