正则表达式替换foreach_if_elseif_else

$pattern=array(
//匹配模板中的标签对应{$test}
// '#\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}#',
'#'.$this->left.'\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*'.$this->right.'#',
//匹配模板中的foreach或者loop
'#'.$this->left.'\s*(loop |foreach)\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*'.$this->right.'#',   //对应{foreach $userInfo}或{loop $userInfo}

'#'.$this->left.'\s*\/(loop|foreach|if)\s*'.$this->right.'#i',

//对应{/foreach}或{/loop}或{/if}

'#'.$this->left.'\s*([K |V])\s*'.$this->right.'#',   //对应{K}或{V}
//匹配if else else if elseif
'#'.$this->left.'\s*if\s*(.* ?)\s*'.$this->right.'#i',   //对应{if $username=="king"}

'#'.$this->left.'\s*(else if|elseif)(.* ?)\s*'.$this->right.'#i',

//对应{elseif $a==1}或者{else if $a==1}

'#'.$this->left.'\s*else\s*'.$this->right.'#i',   //对应{else}
//匹配模板中的注释
'#'.$this->left.'\s*(\#|\*)(.*?)(\#|\*)\s*'.$this->right.'#'   //对应{#注释123#}
);

$replacement=array(

'value["$1"]; ?>',

{$test}替换成value["$test"];

'value["$2"] as $K=>$V){ ?>',

{foreach $userInfo}

替换成

value["$userInfo"] as $K=>$V){ ?>

'',

{/foreach}替换成

'$$1; ?>',

{K}替换成$K; ?>

'$1){ ?>',

{if $a>1}替换成$a>1){ ?>

'$2){ ?>',

{elseif $a>1}替换成$a>1){ ?>

'',

{else}替换成
''//模板中的注释用空白替

{#我是注释,你看不见我#}替换成空白

);

preg_replace($pattern,$replacement,$subject);


将php原生代码开头和结束符实体化<?php ?>

$pattern='#<\?(=|php |)(.+?)\?>#is';

$replacement='<?$1$2?>';

preg_replace($pattern,$replacement,$subject);



你可能感兴趣的:(PHP模板引擎)