2016-09-20 65 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];