【发布时间】:2015-04-19 13:55:49
【问题描述】:
我试图在一个巨大的 xml 文件 (1GB) 之间进行“搜索替换”。 我发现这个很棒的代码在我的文件上使用 str_replace 时可以完美运行-
<?php
function replace_file($path, $string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
return rename($temp, $path);
}
replace_file('myfile.xml', '<search>', '<replace>');
到目前为止一切顺利,效果很好。
现在我将 str_replace 更改为 preg_replace 并将搜索值更改为 '/^[^]/' 所以代码看起来像这样-
<?php
function replace_file($path, $string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, preg_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
return rename($temp, $path);
}
replace_file('myfile.xml', '/[^<search>](.*)[^</search>]/', '<replace>');
我在第 16 行收到错误“preg_replace unknown modifier”'d' 第 16 行是 -
file_put_contents($temp, preg_replace($string, $replace, fgets($file)), FILE_APPEND);
【问题讨论】:
-
查看导致此错误的
$string的实际值会很有启发意义。我的猜测是它包含/d。 -
好吧,我试试 $string= '/[^
](.*)[^ ]/'。 'c' insted of 'd' 出现错误,但我不知道为什么会出现错误。 -
你一开始就没有理解错误信息。让我看看我们是否有它的副本,我很确定有。 - 编辑: 就是这样。在提出问题之前,请重新创建您想从头开始 询问的示例,并使用尽可能少的代码和数据来演示问题(切勿采用具体的实时代码)。在提出新问题之前也要先搜索。