【问题标题】:Dealing with huge xml file using preg_replace [duplicate]使用 preg_replace 处理巨大的 xml 文件 [重复]
【发布时间】: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' 出现错误,但我不知道为什么会出现错误。
  • 你一开始就没有理解错误信息。让我看看我们是否有它的副本,我很确定有。 - 编辑: 就是这样。在提出问题之前,请重新创建您想从头开始 询问的示例,并使用尽可能少的代码和数据来演示问题(切勿采用具体的实时代码)。在提出新问题之前也要先搜索。

标签: php xml


【解决方案1】:

[] 在 PCRE 中是一个字符类。使用[^&lt;category&gt;],您实际上与[^&lt;&gt;acegorty] 匹配相同。您正在匹配字符(或字节),而不是单词。

PCRE 无论如何都不是最好的解决方案。使用XMLReaderXMLWriter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 2010-11-13
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多