在 PHP 中替换文件内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3574999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:16:56  来源:igfitidea点击:

Replacing file content in PHP

phpfilefile-iopreg-replacereplace

提问by Emanuil Rusev

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

我需要一个类似于preg_replace的函数,但我需要它来处理文件/文件内容而不是字符串。

回答by codaddict

You can do:

你可以做:

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

回答by ircmaxell

@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.

@codacci 的答案对于小文件来说已经足够了(如果文件的大小在 MiB 以下,我将如何实现它)。但是它会占用大量内存,因此在读取大文件时应该小心。

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...

这将使内存使用量非常低,同时处理潜在的巨大(GiB 或 TiB)文件......

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)...

哦,另一个很酷的事情是它可以内联编辑不同的流类型。我的意思是您可以从 HTTP 流中读取、内联编辑和写入文件流。它非常强大(因为您可以链接这些过滤器)...

回答by DarkReverser

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

?>