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

混江龙づ霸主 提交于 2019-12-02 23:49:02

问题


I wanna replace braces with <?php ?> in a file with php extension. I have a class as a library and in this class I have three function like these:

 function replace_left_delimeter($buffer)
{
    return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}

function replace_right_delimeter($buffer)
{
    return(str_replace("}", "; ?> ", $buffer));
}

function parser($view,$data)
{
    ob_start(array($this,"replace_left_delimeter"));
    include APP_DIR.DS.'view'.DS.$view.'.php';
    ob_end_flush();
}

and I have a view file with php extension like this:

{tmp} tmpstr

in output I save just tmpstr and in source code in browser I get

<?php echo $tmp; ?> 
tmpstr

In include file <? shown as <!--? and be comment. Why?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/33007283/how-can-i-replace-braces-with-php-in-php-file

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