PHP:用字符串替换php代码

时间:2015-05-28 12:19:42

标签: php replace

我想在字符串中替换php代码并从服务器

运行
$x = 1;
$string = "OK:{first}Yes{second}No";

我希望replace if($x == 1){ {first}} else { {second}

运行后echo $string,我希望结果为html:

  

行:是

2 个答案:

答案 0 :(得分:4)

你是怎么想出这种方法的?为什么不简单:

$string = $x == 1 ? 'OK:Yes' : 'OK:No';

根据$ x的值,这会得到你想要的字符串。

另外,如果你字面意思意味着你想在 PHP代码本身上进行搜索n替换(如@OllyTenerife所假设的那样),那么你打算去将它写入稍后要执行的文件中,还是使用eval()或其他东西?听起来不像是正确的轨道......在这种情况下,重塑你的代码。

答案 1 :(得分:0)

$string = str_replace("{first}","if($x == 1)",$string);
$string = str_replace("{second}","} else {",$string);