需求:写模版引擎
原来的字符串:sfsdafsadfsadfsdfsdfsdfs{任意字符}gdfgdsfgdfgdf
其中任意字符里必须是a到z和-开头
如 {time()}替换成<?php echo time() ?> ,,,,, {file_get_contents}替换成<?php echo file_get_contents ?>
注意:{}里面的()可有可无,最多一次
我是这样写的,一直错误
$new_str=preg_replace('/\{\s*([a-z|A-Z]*)\s*\}/is','<?php echo \\1 ?>',$new_str);
输出:
<?php echo time ?>请按照我这样写 必须有\\1这样的

解决方案 »

  1.   

    本帖最后由 xuzuning 于 2012-10-10 17:34:09 编辑
      

  2.   

    $new_str=preg_replace('/\{\s*([a-z_]\w+)\s*\}/is','<?php echo \\1 ?>',$new_str);
      

  3.   

    $new_str=preg_replace('/\{\s*([a-z_]\w+(\(\))?)\s*\}/is','<?php echo \\1 ?>',$new_str);
      

  4.   

    $new_str = 'dsafs{aaa}fff{time()}xxx';
    echo $new_str=preg_replace('/\{\s*([a-z]+)(?:(\(\)))?\s*\}/isU','<?php echo \\1\\2 ?>',$new_str);dsafs<?php echo aaa ?>fff<?php echo time() ?>xxx
      

  5.   

    $new_str = 'dsafs{aaa}fff{time()}xxx';
    echo $new_str=preg_replace('/\{\s*([a-z]+)(?:(\(\)))?\s*\}/isU','<?php echo \\1\\2 ?>',$new_str);