Dealing with huge xml file using preg_replace



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

No comments:

Post a Comment