Frage

page.html

<body>
   <h1>{{HEADING1}}</h1>  {{CONTENT1}}
   <h2>{{NEWSLETTER}}</h2>
   <h1>{{VAR1}}</h1>  {{VAR2}}
</body>

page.php

$HEADING    = 'Heading';
$CONTENT    = '
              <div align="center">
              -- Content goes here --
              </div>
              ';
$NEWSLETTER = 'newsletter content';
$VAR1       = 'Another Sub Heading';
$VAR2       = 'content';

$File       = file('page.html');
print $File;

1> While the url http://example.com/page.php executes, All the {{VARIABLE}} should replace by the value in $VARIABLE.

2> Also I want to call the PHP loop inside HTML
Something Like

BEGIN WHILE LOOP
CONTENTS
END

What are the best methods (or Regular Expression) to implement these?

War es hilfreich?

Lösung

The below can be used to change the variables $HEADING to {{HEADING}}

   $File          = file('file.html');
   $FContent      = join("", $File);
   $FileContent   = preg_replace("/{{(.*?)}}/e","@$$1", $FContent);

   print $FileContent;

Andere Tipps

what about using a template engine? See Twig

you will have to set the variables in your PHP files like this

return array("variable" => "variable_content");

and then use it in the HTML files this way:

Content: {{variable}}

in the HTML you can also loop with Twig syntax

{% for var in variables %}
   Content: {{var}}
{% endfor %}

You can use str_replace here:

$File = str_replace("{{HEADING}}",$HEADING,$File);
$File = str_replace("{{CONTENT}}",$CONTENT,$File);
print $File;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top