0

I was trying to make a "search replace between for a huge xml file (1GB). I found this great code that is work perfectly while using str_replace on my file-

<?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>');

so far so good and it works great.

Now I changed the str_replace to preg_replace and the search value to '/^[^]/' so the code looks like this-

<?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>');

I get an error "preg_replace unknown modifier" 'd' on line 16 line 16 is -

file_put_contents($temp, preg_replace($string, $replace, fgets($file)), FILE_APPEND);
  • 1
    It would be instructive to see the actual value of `$string` that causes this error. My guess is that it contains `/d`. –  Apr 19 '15 at 14:07
  • Well I try $string= '/[^](.*)[^]/'. I got the error with 'c' insted of 'd' but I don't know why I get the error. – Shimon David Scheff Apr 19 '15 at 14:17
  • You don't understand the error message in the first place. Let me see if we've got a duplicate for it, I'm pretty sure there is. - *Edit:* There it is. Before asking a question, pleaser re-create the example you want to ask about *from scratch* with as little code and data as necessary to demonstrate the issue (never take concrete live-code). Also first search before asking a new question. – hakre Apr 19 '15 at 15:14

1 Answers1

0

[] in PCRE is a character class. With [^<category>] you're actually matching the same as with [^<>acegorty]. You're matching characters (or bytes), not words.

PCRE is not best solution for this anyway. Use XMLReader and XMLWriter.

ThW
  • 19,120
  • 3
  • 22
  • 44