How can I replace braces with <?php ?> in php file?

纵饮孤独 提交于 2019-12-02 13:41:02

do this:

function parser($view,$data)
{
    $data=array("data"=>$data);
    $template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
    $replace = array();
    foreach ($data as $key => $value) {
        #if $data is array...
        $replace = array_merge(
            $replace,array("{".$key."}"=>$value)
            );
    }

    $template=strtr($template,$replace);
    echo $template;
}

and ignore other two functions.

What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.

You will need to instead preprocess the PHP source file before evaluating it, e.g.

$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);

However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.

How does this work:

process.php:

<?php

$contents = file_get_contents('php://stdin');

$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;

bash script:

process.php < my_file.php

Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.

Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!