You could just change the replacement to:
preg_replace("/(---\\\$_SESSION\\['(.+?)'\\]---)/", "\${\$_SESSION['\\2']}", $html)
but I wouldn't at all recommend it. As always, eval
is a big clue you're doing something wrong.
Non-templating uses of $
in 1.html or the session variable will cause errors. Arbitrary code in 1.html or the session variable can be executed via the ${...}
syntax, potentially compromising your server. Less-than signs or ampersands in the session variable will be output as-is, leading to cross-site-scripting attacks.
A better strategy is to keep the string as just a string, not a PHP command. Find the ---...---
sections and replace those separately:
$parts= preg_split('/---(.+?)---/', $html, null, PREG_SPLIT_DELIM_CAPTURE);
for ($i= 1; $i<count($parts); $i+= 2) {
$part= trim($parts[$i]);
if (strpos($part, "\$_SESSION['")==0) {
$key= stripcslashes(substr($part, 11, -2));
$parts[$i]= htmlspecialchars($_SESSION[$key], ENT_QUOTES);
}
}
$html= implode('', $parts);
(Not tested, but should be along the right lines. You may not want htmlspecialchars
if you really want your variables to contain active HTML; this is not usually the case.)