0

I have a text file with the follow content:

This is a static content

{{ echo "Hello World" }}

The file is named test.txt

What I want is to parse this file using PHP and create a new file with the following content:

This is a static content

Hello World

As you can see the code inside the curly braces: {{}} needs to be executed before save to the target file. I don't know where to start to achieve my goal.

1
  • use a template engine which accepts plugins as well, i think this is what is needed in your qustion, instead of developing a template engine all over (except if you want to do that) Commented May 27, 2015 at 16:42

1 Answer 1

1

Something like

echo preg_replace_callback('/\{\{(.*?)\}\}/', function($match) {
    ob_start();
    eval($match[1] . ';');
    $out = ob_get_clean();

    return $out;
}, $string);

should do the job.

Demo: http://3v4l.org/nYT31

Sign up to request clarification or add additional context in comments.

2 Comments

your solution is working perfectly, but do you know any other approach without eval (some hosting provider don't allow eval).
Not if you want to execute php code, sorry. Maybe you want build a template parser like Smarty o Twig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.