php - search string with preg_replace

$html = file_get_contents("1.html");
eval("print \"" . addcslashes(preg_replace("/(---(.+?)---)/", "\\2", $html), '"') . "\";");

This searches an string and replaces ---$variable--- with $variable.

How can I rewrite the script so that it searches for ---$_SESSION['variable']--- and replaces with $_SESSION['variable']?




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 wanthtmlspecialchars if you really want your variables to contain active HTML; this is not usually the case.)

People are also looking for solutions to the problem: [PHP/JavaScript]: Call PHP file through JavaScript code with argument


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.