2016-09-20 57 views
1

我的php腳本獲取了一個json配置文件。在這種情況下,$ json-> autowelcome是「Hello {user},歡迎!」把某些字符串當作變量

我想讓PHP將{user}解釋爲$ user。我怎樣才能做到這一點?

 // Answer to tickle every 5 seconds 
     if (time() - dataAPI::get($key) >= 5) { 
      dataAPI::set($key, time()); 
      $bot->network->answerTickle($who); 
      $name = $bot->users[$who]->getRegname(); 
       $bot->network->sendMessageAutoDetection($who, $bot->botData['ontickle'], 2,true); 

     } 
+1

方法的*邪惡*的eval()想到 – nogad

+1

郵編是相關的問題,請文本。 – YvesLeBorg

+0

如果autowelcome是一個你可以使用的函數['str_replace'](http://php.net/manual/en/function.str-replace.php),就不能看到'$ json-> autowelcome'背後的代碼。在其中像'str_replace(「{user}」,$ user,「」Hello {user},welcome!「)' –

回答

3

我可以建議你使用str_replace。更簡單的方法。

例:

$string = 'Hello {name}!'; 
$search[] = '{id}';   $replace[] = $user->getID(); 
$search[] = '{name}';   $replace[] = $user->getNick(); 
$search[] = '{regname}';  $replace[] = $user->getRegname(); 
return str_replace($search, $replace, $string); 
+0

假定你知道所有可能的變量,以 – nogad

+0

開頭@nogad hehe,他是項目的開發人員i我正在測試,他知道所有的變數。 –

-1

使用的preg_match

<?php 
$dog='woof'; 
$string="cat {dog} fish"; 

preg_match('#(.*)(\{(.*)\})(.*)#',$string,$match); 

echo $match[1].${$match[3]}.$match[4];