This is a tricky one...I am trying to replace some strings in a file that i hold in array. Because there are a lot of files...i've been trying to find the fastest way possible. I tried this (which worked) but it was slow.
- First parsed all the files and got an array of the values i want to change (lets say 500).
- Then I wrote a foreach loop to parse through the files one by one.
- Then inside that, another foreach loop to go through the values one by one preg_replacing the file for any occurrences of the array value.
This takes forever though cause not all files need to be parsed with 500 array elements. So i am changing the code now like this:
- Parse every file and make an array of the values i want to replace.
- Search the file again for all the occurrences for each array value and replace it.
- Save the file
I think this will be much faster that the old way...The problem i am having though now is with the read/write loop, and the array loop... I want to do this as fast as possible...cause there will be a lot of files to parse and some have 100+ values. So far i got this in a function.
function openFileSearchAndReplace($file)
{
$holdcontents = file_get_contents($file);
$newarray = makeArrayOfValuesToReplace($holdcontents);
foreach ($newarray as $key => $value) {
$replaceWith = getNewValueFor($value);
$holdcontent = preg_replace('/\\b'.$value.'\\b/', $replaceWith, $holdcontents);
}
file_put_contents($file, $holdcontent, LOCK_EX); //Save and close
}
Now, this doesnt work...it just changes 1 value only because i have file_put_contents and file_get_contents outside of the foreach. (Not to mention that it replaces values that it shouldnt replace. Probably cause the read/write are outside of the loop.) I have to put them inside to work..but thats gonna be slow..cause it take 3-4seconds per file to do the change since there are a lot of elements in the array.
How can i "Open the file", "Read it", "Change ALL values first", "Then save close the file", so i can move to the next.
EDIT: Maybe i am not explaining it well i dont know...or is this too complicated....I have to parse the array of values...there is no way i can avoid that...but instead of (In every loop), i open the file search and replace 1 value, close the file.....I want to do this: Open the file, get the content in an array or string or whatever. For all the values i have keep replacing the text with the equivalent value, and when all the values are done...that array or string write to the file. So i am only opening/closing the file once. Instead of waiting for php to read/write/close all the time.
-Thanks
sed
on these files would be a lot faster than reading->parsing->processing->saving – Mohammad AbuShady Feb 23 at 15:27g
modifier doesn't exist in PHP. – Casimir et Hippolyte Feb 23 at 15:33makeArrayOfValuesToReplace()
andgetNewValueFor()
. Could you post these two functions? – Casimir et Hippolyte Feb 23 at 15:56