如何用变量替换<! - etc - >

时间:2012-08-01 01:36:56

标签: php replace

我有一个变量$email需要替换我脚本中的所有<!--email-->

有人可以指导我做到这一点的最佳方式,目前正在做:

$email = $_SESSION["email"];
str_replace("<!--email-->",$email,"<!--email-->") 

2 个答案:

答案 0 :(得分:1)

$email = $_SESSION["email"];
$filename = 'script.php';
$script = str_replace("<!--email-->",$email,file_get_contents($filename));

它将更改您文件中的所有内容,您只需保存或回显它

答案 1 :(得分:0)

这是一个4个班轮,基本上会抓住你所有的<!--tag-->并用适当命名的变量替换它们:

$string = "string or output from file_get_contents()";

preg_match_all("/<!--([A-z0-9_]+)-->/", $string, $matches);

foreach($matches[1] as $match){
$string = preg_replace("/<!--([$match]+)-->/i", ${$match}, $string);
}

echo $string;