2014-10-15 3 views
2

나는 PHP로 AJAX를 통해 명령을 게시하는 간단한 JS 터미널 쉘 에뮬레이터를 구축하고 있습니다.
보안을 제쳐두고 두십시오. 이는 학습 및 데모 목적으로 만 사용하십시오. 이제 문제는 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 testserverPHP - str_replace가 원래 문자열을 반환

을 반환?

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; 
} 
+0

이 environment.json –

+0

의 내용을 표시하십시오 이유는 않는 str_replace의 사용에서 찾을 수없는, 그래서 조합'$ var','$의 val'과'게시하시기 바랍니다 $ cmd'를 사용합니다. – Alexander

+1

'strpos ('strpos ($ cmd, '$'))!를 사용해야하므로'strpos'를주의 깊게 읽으십시오. 처음에 찾으려는 단어가'0'이 아니라'false'가 아닙니다. == false' – Sal00m

답변

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); 
    } 
+0

이 있습니다. 하지만 왜 그런지 이해가 안되, 너 설명 할 수있어? 그럴 것입니다 ... –

+0

루프를 다시 실행할 때마다 "초기"데이터 ($ cmd)를 가져 와서 바꿉니다. 따라서 반복 할 때마다 이전 루프에서 변경 한 내용을 잃어 버리게됩니다. – blue112

관련 문제