[英]replace tags with PHP variables using preg_match
{$thisname}
should be converted to <?php echo $thisname; ?>
{$thisname}
应该转换为<?php echo $thisname; ?>
<?php echo $thisname; ?>
. <?php echo $thisname; ?>
。
{thisname}
should be converted to <?php echo $thisname; ?>
{thisname}
应该转换为<?php echo $thisname; ?>
<?php echo $thisname; ?>
. <?php echo $thisname; ?>
。
{$this.movie.games}
&& {$this.new}
should be converted respectively to <?php echo $this["movie"]["games"]; ?>
{$this.movie.games}
&& {$this.new}
应该分别转换为<?php echo $this["movie"]["games"]; ?>
<?php echo $this["movie"]["games"]; ?>
and <?php echo $this["new"]; ?>
<?php echo $this["movie"]["games"]; ?>
和<?php echo $this["new"]; ?>
<?php echo $this["new"]; ?>
. <?php echo $this["new"]; ?>
。
Use a templating system, I suggest using http://phpsavant.com/ although it looks like you're more interested in Smarty or Dwoo 使用模板系统,我建议使用http://phpsavant.com/,尽管您似乎对Smarty或Dwoo更感兴趣
There's no need to re-invent the wheel :) 无需重新发明轮子:)
$tpl = 'Name: {$name}, Surname: {surname}, City: {$person.address.city}';
function tpl2php($m){
$var = $m[1];
if(strpos($var,'.')){
$varArr = explode('.',$var);
$var = $varArr[0];
for($i=1;$i<count($varArr);$i++){
$var .= '["' . $varArr[$i] .'"]';
}
}
return '<?php echo $' . $var . '; ?>';
}
$php = preg_replace_callback('/{\$?([_a-z][\w\.]+[\w])}/iS','tpl2php',$tpl);
// Name: <?php echo $name; ?>, Surname: <?php echo $surname; ?>, City: <?php echo $person["address"]["city"]; ?>
使用str_replace函数。
preg_replace and regular expressions are more flexible than str_replace, especially if you have to parse a string like this.movie to $this["movie"]. preg_replace和正则表达式比str_replace更灵活,尤其是当您必须将类似this.movie的字符串解析为$ this [“ movie”]时。 It will not be an easy task though. 但是,这将不是一件容易的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.