I am creating a function that replaces certain parts of a string with predefined constants, for this I have created this function:
<?php
function ReplaceWithPath($string)
{
$toReplace = ["~~BASEPATH~~" => ABSPATH, "~~LIBPATH~~" => LIBPATH];
foreach ($toReplace as $replace => $replacement)
{
if (preg_match($replace, $string))
return str_replace($replace, $replacement, $string);
else
continue;
}
return false;
}
?>
But for some reason, when I use it it does not give me a proper result, but instead boolean false.
I am using the function in my config file as such:
<?php
$cfg_file = str_replace("\\", "/", dirname(__FILE__)) . "/web.config.xml";
$cfg = simplexml_load_file($cfg_file);
define("ABSPATH", $cfg->paths->basepath);
require_once 'library/functions/ReplaceWithString.php';
define("LIBPATH", ReplaceWithPath($cfg->paths->libpath));
var_dump(LIBPATH);
?>
The part of the XML file in question is this:
<paths>
<basepath>E:/projects/php/site/site/</basepath>
<libpath>~~BASEPATH~~library/</libpath>
<classpath>~~LIBPATH~~class/</classpath>
<traitpath>~~LIBPATH~~trait/</traitpath>
</paths>
I need to be able to change the parts that are ~~BASEPATH~~ with ABSPATH but it just return boolean false.
Edit
After testing, I have found that it is the fact that there are multiple constants in the array ($toReplace) that is causing this not to work. WHY IT DO DIS?!?!?!
New function created:
function ReplacePathPart($path)
{
$replaced = "";
$toReplace = array(
'!!BASEPATH!!'=>ABSPATH,
'!!LIBPATH!!'=>LIBPATH
);
foreach ($toReplace as $replace => $replacement)
{
$replaced = str_replace($replace, $replacement, $path);
}
return $replaced;
}
Amended config file:
<?php
$cfg_file = str_replace("\\", "/", dirname(__FILE__)) . "/config/web.config.xml";
$cfg = simplexml_load_file($cfg_file);
define("ABSPATH", $cfg->paths->basepath);
require_once 'library/functions/ReplaceWithString.php';
define("LIBPATH", ReplacePathPart($cfg->paths->libpath));
define("CLASSPATH", ReplacePathPart($cfg->paths->classpath));
print ABSPATH . " |abspath<br />";
print LIBPATH . " |libpath<br />";
print CLASSPATH . " |classpath<br />";
?>
Output:
E:/projects/php/site/site/ |abspath
!!BASEPATH!!library/ |libpath
!!BASEPATH!!library/class/ |classpath
$replacedResult = str_replace(array_keys($toReplace), array_values($toReplace), $string);?~~BASEPATH~~,~will be seen as delimiter for yourpreg_match()call and your regex will fail with unescaped delimitersstr_replace()also can take arrays as argument, as I said just use:$replacedResult = str_replace(array_keys($toReplace), array_values($toReplace), $string);you overthink this way too much.; Now you use$patheach source which doesn't change and save it in$replaced, that's why only the last one gets replaced