Bobby
Bobby

Reputation: 3

how do i replace some matched template tags in php

I have this template file as HTML and willing to replace all matched tags eg [**title**] etc with the right content then write to disk as PHP file. I've done series of search and none seems to fit my purpose. Below is the HTML code. The problem is it doesn't always replace the right tag?

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>[**title**]</title>
  </head>
  <body>
  <!--.wrap-->
  <div id="wrap">
  <!--.banner-->
  <div class="banner">[**banner**]</div>
  <!--/.banner-->

  <div class="list">
    <ul>[**list**]</ul>
  </div>

  <!--.content-->
  <div class="content">[**content**]</div>
  <!--/.content-->

  <!--.footer-->
  <div class="footer">[**footer**]</div>
  <!--/.footer-->

  </div>
  <!--/.wrap-->

</body>
</html>

This is what I have tried so far.

<?php
    $search = array('[**title**]', '[**banner**]', '[**list**]'); // and so on...
    $replace = array(
        'title' => 'Hello World', 
        'list' => '<li>Step 1</li><li>Step 2</li>', // an so on
    ); 

    $template = 'template.html';
    $raw = file_get_contents($template);
    $output = str_replace($search, $replace, $raw);
    $file = 'template.php';
    $file = file_put_contents($file, $output);

?>

Upvotes: 0

Views: 1890

Answers (2)

AtkinsSJ
AtkinsSJ

Reputation: 482

The problem in your code is that you're using keys in the $replace array. str_replace just replaces based on the position in the array, so the keys do nothing.

So, you have [**banner**] as the second item in $search, so it would replace it with the second item in replace, which is <li>Step 1</li><li>Step 2</li>.

If you want to automatically do it by the key (so [**foo**] is always replaced with $replace['foo'], you might want to look at using regular expressions. I knocked up a quick piece of code which worked when I tested it, but there might be bugs:

<?php
function replace_callback($matches) {
        $replace = array(
            'title' => 'Hello World', 
            'list' => '<li>Step 1</li><li>Step 2</li>', // an so on
        );

    if ( array_key_exists($matches[1], $replace)) {
        return $replace[$matches[1]];
    } else {
        return '';
    }
}

$template = 'template.html';
$raw = file_get_contents($template);

$output = preg_replace_callback("/\[\*\*([a-z]+)\*\*\]/", 'replace_callback', $raw);

$file = 'template.php';
$file = file_put_contents($file, $output);

Upvotes: 1

helle
helle

Reputation: 11660

str_replace is the right function. but the $replace array has to hold the values in the same flat structur like $search

so:

$replace = array('Hello World', '<li>Step 1</li><li>Step 2</li>', // an so on    ); 

Upvotes: 0

Related Questions