Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace placeholder in template with php function

Tags:

regex

replace

php

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.

like image 909
denii Avatar asked Feb 04 '26 19:02

denii


1 Answers

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);
like image 125
sinisake Avatar answered Feb 06 '26 09:02

sinisake