1

Is it possible to change some file-contents from a file before including it?

I basically want to make a really simple template system. To do so I just include the templates, which are HTML files being able to contain PHP code.

My problem: To make it easier to use I want to replace all {something} in the to be included contents with <?php echo $something; ?>. Is it somehow possible?

Tom Tom
  • 3,680
  • 5
  • 35
  • 40
Fly
  • 810
  • 2
  • 9
  • 28
  • 1
    Welcome to SO. You should use the code format in your posts to make them more easier to read. I edited this one for you. – Tom Tom Apr 12 '15 at 20:43

1 Answers1

0

Yes, this is possible. You retrieve the file its contents with for example file_get_contentsmanual and then use a regular expression to find & replace placeholders with variables. See for example this answer for a very simple approach.

Do note that there are already a lot of template engines out there. Twig, Dwoo and Smarty can all do what you want and more. In fact, plain PHP by itself can be used as a template engine but there are arguments against that, too.

Community
  • 1
  • 1
Elias
  • 1,532
  • 8
  • 19
  • Problem is that I need to execute PHP Code in the template too. Most of the template will only be HTML or those `{something}`s, but the user (Well, me) should have the possibility to add code in between PHP Tags. – Fly Apr 12 '15 at 20:49