PHP: Insert Text Into File at Position

March 7th, 2012 Leave a comment
Like the article?
PHP Inserted Text

This is a small PHP tip I used to insert arbitrary text into a file at a specific position. There are times when you need to insert (or rather, append at a given position) an arbitrary text into a file from within your PHP application. It only takes a few lines of code, but I didn’t find an exact solution to this on Google, so I decided to share my own solution with you. The link below is as close as I got to what I needed: http://www.neoseeker.com/forums/45/t1544597-php-append-text-to-file-at-specific-position/, but the code from there was overwriting the contents of the file instead of just appending to it.

NOTE: This is not an ideal solution for large files, since it uses file_get_contents() method to extract the entire contents of the file into a variable. For larger files you might want to consider a scheme that uses stream buffering.

/**
* 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);
}

To use it, make sure the file you are inserting into contains the “marker” text to mark the location where the text is to be inserted. The file in the article image above uses a line:

#### INSERT TEXT MARKER ####

as the marker. Here is an example:

$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!";
}

Resulting my_file:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !(map\.xml(\.gz)?)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} \.(css|js)$ [NC]
    RewriteRule .* - [L]
</IfModule>

#### INSERT TEXT MARKER ####
I am a PHP inserted text!!!

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

My own use-case is our class scheduling system at LearnComputer. When a new class is scheduled, a unique URL is generated for that class. The system uses the start date of the class as its unique URL identifier. Here is an example:

If the class is re-scheduled to a different start date, the URL above would have to change. When this happens, I use the code above to automatically add a RewriteRule to .htaccess file to add a re-direct from the old URL to the new URL:

#### INSERT TEXT MARKER ####
RewriteRule ^(training/php/php-javascript-ajax-jquery)/2012-14-05/?$ "$1/2012-16-06/" [R=301,L]

Hope this little tip helps you stay on track with your PHP project and spend less time browsing forums and more time writing some quality PHP code! If you need more than a little tip, consider enrolling in one of our PHP training courses. Also, if you have alternate techniques you used, or if you have any other tips for our readers, please leave a comment below.

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!

Comment