Hey,
I call this a mystery because it's the longest debug i've ever done on any single function. And because it makes no logical sense, as according to the documentation and my tests, it works fine.
The Problem:
Let's say you have a config file, and you want to preg_replace and change variables inside this config php file. Sometimes it can be an array, sometimes it can be a single variable. And of course it's in a loop.
if(!empty($Config)){
foreach($form as $key => $val){
if(is_array($val)){
$array = '';
for($i = 0; $i < count($val); $i++){
if($i == 0)$array .= 'array(';
$array .= '\''.$val[$i].'\'';
if($i == count($val)-1){
$array .= ')';
break;
} else {
$array .= ', ';
}
}
$val = $array;
}
if($val == 'Yes' || $val == 'Show')$val = 1;
if($val == 'No' || $val == 'Hide')$val = 0;
$Config = preg_replace("/(\\\$config\['".$component."'\]\['".$key."'\] = [']?)(?(?=array)[a-zA-Z0-9()',\s]*|[a-zA-Z0-9\s,-_]*)([']?);/i", "$1".$val."$2;", $Config);
echo '<br><br>'.htmlspecialchars($Config);
}
}
Now, ignore the stuff under is_array($val)... because that's just to convert from an array into a literal string so that it can be preg-replaced in the file.
$Config comes from file_get_contents, a config.php file.
I echoed the result to see what would happen after a replace.
In this loop, it does NOT work. Instead of replacing the line with the correct $key and $component with the original $key/$component AND my new $val, it replaces that $key/$component line with a SINGLE SEMICOLON. This means that the SEARCH of preg_replace is sucessful, yet it does not record $1, $2, and $val somehow these 3 variables get magically deleted, mysterious enuf?
Get's worse, so of course as any sensible programmer, I isolated preg_replace and tested it on a single file with just $Config, and $key = 'something' and $component = 'something' and $val = 'somethingNew'.... the result is... it works PERFECTLY... so how can something isolated work outside a script alone, but not work when it's in a bigger script. Well there must be something in my bigger script that is changing and affecting my preg_replace, well how the hell can that be??? I haven't used any function that interferes with preg_replace, and I do not believe I used any incorrect methods of preg_replace...
Btw, $form is just a big array of $POST/$GET which I can use to change the config file.
Its either a php bug, a mystery, or something stupid that I missed which is highly unlikely. Any help would be appreciated, sorry for the long post.