denii
denii

Reputation: 99

Replace placeholder in template with php function

Short and clear. I'm not good at regex because I never understood it. But when you look at this simple template, would you say it's possible to replace the %% + the content of it with php brackets + add function brackets to it like this:

Template:

<html>
<head>
    <title>%getTitle%</title>
</head>
<body>
    <div class='mainStream'>
        %getLatestPostsByDate%
    </div>
</body>
</html>

It should replace it to this:

<html>
<head>
    <title><?php getTitle();?></title>
</head>
<body>
    <div class='mainStream'>
        <?php getLatestPostsByDate();?>
    </div>
</body>
</html>

Is this possible? If yes, how? If anyone got a good tutorial for regEx which explains it even for not so smart guys, I'd be very thankful.

Thanks in advance.

Upvotes: 3

Views: 930

Answers (2)

sinisake
sinisake

Reputation: 11328

This could be a good start. Get all between your custom tags (%%), and replace it with php code.

https://regex101.com/r/aC2hJ3/1

regex: /%(\w*?)%/g. Check explanation of regex at the right hand side (top), and generated code... it should help.

$template=file_get_contents('template.php');

    $re = "/%(\\w*?)%/"; 

    $subst = "<?php $1(); ?>"; 

    $result = preg_replace($re, $subst, $template);

file_put_contents('template.php',$result);

Upvotes: 3

Rohit Gupta
Rohit Gupta

Reputation: 4193

Try this

$html = str_replace ('%getLatestPostsByDate%', '<?php getLatestPostsByDate();?>', $html);

If, however you are looking for a generic solution then you have to use regex

Upvotes: 1

Related Questions