0

I would create a system that replace tags in the HTML code trough PHP, I can do that trough the function preg_replace, but how I can create a loop?

For example:

A part of the HTML-file:

<div class="users">
{users}
    <div class="single-user">
        {lastname}, {firstname}
    </div>
{endusers}
</div>

Is must be so:

<div class="users">
    <div class="single-user">
        Person1, Firstname1
    </div>
    <div class="single-user">
        Person2, Firstname2
    </div>
    <div class="single-user">
        Person3, Firstname3
    </div>
</div>

Thanks for reading.

Robiin
  • 11
  • 6

1 Answers1

-1

Assuming the information is being pulled from a database, you can use something like this:

$result = mysql_query("SELECT * FROM table1", $link);

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
 $display = $upperTemplate . $row[0] . $middleTemplate . $row[1] . $lowerTemplate;  
}

This also assumes the template is in three parts, but if you already have the code to display an entry, you can just put that in the content of the loop.

If the information is stored in a multi-dimensional array, you can for a FOR loop instead.

for($i = 0; $i < sizeof($array); $i++) {
 $display = $upperTemplate . $row[0] . $middleTemplate . $row[1] . $lowerTemplate;  
}

I hope this helps.

Edit: Here's the PDO version:

$query = "SELECT * FROM table1";
$result = $db->prepare($query);
$result->execute();

while ($row = $result->fetch())) {
 $display = $upperTemplate . $row[0] . $middleTemplate . $row[1] . $lowerTemplate;  
}
  • 1
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Sep 01 '14 at 15:47
  • I would create a template parser, the data is from an database trough PDO, but I know how that works. I would to do it trough {users}/{endusers} tags. – Robiin Sep 01 '14 at 15:48
  • I updated it to include a quick PDO version. Didn't test it, just threw it together, but I believe it'll do what you want. – Christopher Esbrandt Sep 01 '14 at 15:56