PHP - str_replace返回原始字符串

时间:2014-10-15 08:05:25

标签: php ajax

我正在构建一个简单的JS终端shell模拟器,它通过AJAX将其命令发布到PHP 请将安全放在一边,这仅用于学习和演示目的。 现在我的问题是,str_replace()将无法按预期工作,实际上,它返回未更改的输入字符串。它应该像这样工作:
The name of this host is $hostname - > Yes, this string contains a variable - > Replace $hostname with testserver - >返回The name of this host is testserver

我做错了什么?

这是我对echoexport的回复脚本:

<?
// get environment variables from JSON
$vars = json_decode(file_get_contents('environment.json'), true);

// get request params
$method = $_SERVER['REQUEST_METHOD'];
$action = $_POST['action'];
$data = $_POST['data'];

switch ($action) {

case 'echo':
    $cmd = $data;

        // if the string in question contains a variable, eg. "the time is $time"
        if (strpos($cmd,'$')) {
        $output = '';

        // for each environment variable as variable => value
        foreach ($vars as $var => $val) {

            // replace every variable in the string with its value in the command
            $output = str_replace($var,$val,$cmd);
        }
        echo $output;
    } else { 

        // if it does not contain a variable, answer back the query string 
        // ("echo " gets stripped off in JS)
        echo $cmd; 
    }
break;

case 'export':

    // separate a variable declaration by delimiter "="
    $cmd = explode('=',$data);

    // add a $-sign to the first word which will be our new variable
    $var = '$' . array_shift($cmd);

    // grab our variable value from the array
    $val = array_shift($cmd);

    // now append everything to the $vars-array and save it to the JSON-file 
    $vars[$var] = $val;
    file_put_contents("environment.json",json_encode($vars));
break;
}

1 个答案:

答案 0 :(得分:2)

更好地使用:

if (strpos($cmd,'$') !== false) {

然后,每个替换都将“第一”数据作为其输入数据。你应该这样做:

    $output = $cmd;

    // for each environment variable as variable => value
    foreach ($vars as $var => $val) {

        // replace every variable in the string with its value in the command
        $output = str_replace($var, $val, $output);
    }