Replacing file content in PHP

php file set contents
php file_put_contents
php fopen
php write to file
php create file in directory
php overwrite file
how to save html form data to text file using php
php stream to file

I need a function just like preg_replace but instead of strings I need it to work with files / file content.

You can do:

$file = 'filename';
file_put_contents($file,str_replace('find','replace',file_get_contents($file)));

file_put_contents - Manual, We can apply search and replacement of content by using str_replace and then save the file with changed content. Here is the code <?Php $filename=$_GET['  Search/replace is easier from a shell prompt or an editor, but what if you have to do the same programatically in php. File_SearchReplace is a pear package that helps you search/replace in files through a nice object oriented interface. Installation Pear installation as usual is simple.

@codaddict's answer is quite sufficent for small files (and would be how I would implement it if the size of the file was under a MiB). However it will eat up a ton of memory, and as such you should be careful when reading large files.

If you want a much more memory friendly version, you could use stream filters...

class ReplaceText_filter extends php_user_filter {
    protected $search = '';
    protected $replace = '';

    public function filter($in, $out, &$consumed, $closing) {
        while ($bucket = stream_bucket_make_writable($in)) {
            $bucket->data = str_replace(
                $this->search, 
                $this->replace, 
                $bucket->data
            );
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }

    public function onCreate() {
        if (strpos($this->filtername, '.') === false) return false;
        list ($name, $arguments) = explode('.', $this->filtername, 2);
        $replace = '';
        $search = $arguments;
        if (strpos($arguments, '|') !== false) {
            list ($search, $replace) = explode('|', $arguments, 2);
        }
        if (strpos($search, ',') !== false) {
            $search = explode(',', $search);
        }
        if (strpos($replace, ',') !== false) {
            $search = explode(',', $replace);
        }
        $this->search = $search;
        $this->replace = $replace;
    }
}
stream_filter_register('replacetext.*', 'ReplaceText_Filter');

So, then you can append an arbitrary stream filter. The filter's name determines the arguments:

$search = 'foo';
$replace = 'bar';
$name = 'replacetext.'.$search.'|'.$replace;
stream_filter_append($stream, $name);

or for arrays,

$search = array('foo', 'bar');
$replace = array('bar', 'baz');
$name = 'replacetext.'.implode(',', $search).'|'.implode(',', $replace);
stream_filter_append($stream, $name);

Obviously this is a really simple example (and doesn't do a lot of error checking), but it allows you to do something like this:

$f1 = fopen('mysourcefile', 'r');
$f2 = fopen('mytmpfile', 'w');
$search = array('foo', 'bar');
$replace = array('bar', 'baz');
$name = 'replacetext.'.implode(',', $search).'|'.implode(',', $replace);
stream_filter_append($f1, $name);
stream_copy_to_stream($f1, $f2);
fclose($f1);
fclose($f2);
rename('mytmpfile', 'mysourcefile');

And that will keep memory usage very low while processing potentially huge (GiB or TiB) files...

Oh, and the other cool thing, is it can inline edit differing stream types. What I mean by that is that you can read from a HTTP stream, edit inline, and write to a file stream. It's quite powerful (as you can chain these filters)...

PHP file writing for entering data to an new or existing file, open file, change content, save file - Writing PHP - Programming in PHP ; forum discussion. This system open my file and delete all the code in file underbaba.php, I need a code because I have a lot of files to edit I used scandir and foreach for reading files in all directory c with name underbaba.php, Thanks.

<?php

$pattern = "/created/";
$replacement = "XXXXX";
$file_name = "regex.txt";
$getting_file_contents = file_get_contents($file_name);

echo("Original file contents : " . "<br><br>");
var_dump($getting_file_contents);
echo("<br><br><br>");

if ($getting_file_contents == true) {
  echo($file_name . " had been read succesfully" . "<br><br><br>");

  $replace_data_in_file = preg_replace($pattern, $replacement, $getting_file_contents);
  $writing_replaced_data = file_put_contents($file_name, $replace_data_in_file);
  echo("New file contents : " . "<br><br>");
  var_dump($replace_data_in_file);
  echo("<br><br>");

  if ($writing_replaced_data == true) {
    echo("Data in the file changed");
  }
  else {
    exit("Cannot change data in the file");
  }
}
else {
  exit("Unable to get file contents!");
}

?>

open file, change content, save file, Note: Use FILE_APPEND to avoid deleting the existing content of the file. Syntax. file_put_contents(filename, data, mode, context). Parameter Values. Parameter  Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

PHP file_put_contents() Function, If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace; If find is an array and replace is a string, the​  The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance. Syntax

PHP str_replace() Function, By this tutorial we will learn how to get text file content then replace some strings then put the Duration: 6:54 Posted: Jul 15, 2019 What I’m getting at is that you seem to be brushing aside Chris’ responses: the point being that this tutorial is not simply a “solution” for including a site navigation, but showcases a method for dynamically importing, replacing, and transitioning between external content on the client side. PHP can’t do that (which is not a

Replace string in text file using PHP php#56, Whatever your reasons are for wanting to manipulate files, PHP will happily accommodate them through the use of a handful of functions. You should have read  file_put_contents (string $filename, mixed $data [, int $flags = 0 [, resource $context ]]) : int This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created.

Comments
  • You could pull file contents into a variable by looping over it using fread and then work with preg_replace as you would with a string of text ?
  • Yes but then the updated content should be written into the files it was taken from.
  • So what is the problem to write the content back to the file?
  • You could use the Unix utility sed.
  • PHP supports binary data in strings. Note there is a comment in the manual that the preg fns don't like strings greater than ~100k. However it probably will have problems with null chars in the source string - so read the file in chunks of up to (say) 10k, delimited by nulls, strip any trailing null (and keep it for later), apply the preg to each chunk and write it out again adding the null back if you removed one.
  • The only problem with this answer is when the search terms are located across buckets, especially when dealing with files larger than 8 KiB.
  • Can you add some explanation to this code? else it would be classified as a low quality answer
  • its basic php functions , you can just get the explanation from php.net/docs.php