Page 1 of 1

Help with 'preg_replace_callback'

Posted: Mon Aug 10, 2009 8:13 am
by Swift-R
Hello,

I've came to the following function that executes PHP in HTML templates between {{ and }} tags.

Code: Select all

public function template ( $data )
{
    function loadtemplate_eval ( $arr )
    {
        return ( 'echo stripslashes("' . addslashes ( $arr[0] ) . '");' );
    }
 
    //-----------------------------------------
    // Place the whole code in one line
    //-----------------------------------------
 
    $data = str_replace ( array ( "\n", "\r" ) , array ( "]-,d8=[", "]-,k2=[" ) , $data );
 
    //-----------------------------------------
    // Detect PHP code in template
    //-----------------------------------------
 
    $data = '{{ }}' . $data . '{{ }}';
    $data = str_replace ( '}}', '', str_replace ( array ( '{{', '}}' ), '', preg_replace_callback ( "/\}}(.*?)({{|{{)/", "loadtemplate_eval", $data ) ) );
 
    //-----------------------------------------
    // Arranje template
    //-----------------------------------------
        
    $data = str_replace ( array ( "]-,d8=[", "]-,k2=[" ) , array ( "\n", "\r" ) , $data );
        
    //-----------------------------------------
    // Return
    //-----------------------------------------
 
    return eval ( $data );
}
What it does:

1. It receives $data as a normal HTML template with pieces of PHP code inside of it and instead of using <?php ?> it uses {{ }};

2. It places the whole code in one single line by replacing \n & \r by a random code so preg_replace_callback can read it;

3. It messes around with preg_replace_callback, I don't really know how it works, I found this script in a website and messed with it a little to work the way I want;

4. It arranges the template again, by replacing the random code by \n & \r again.

5. Return the code evaluated.

What's wrong with it:

I want to use this as a template evaluation, to use with several templates. (HTML template between another HTML template, etc...). The problem is, as it uses an echo as you can see in the above code, it always puts the new template above the first template, like this:

Code: Select all

$template_B = '<head></head>';
$template_A = '<html>{{echo $this->template ( $template_B );}}</html>';
 
echo $this->template ( $template_A );
This outputs:

Code: Select all

<head></head><html></html>
And I want it to output:

Code: Select all

<html><head></head></html>
What's the best way to fix this? :)
Thanks.

Re: Help with 'preg_replace_callback'

Posted: Tue Aug 11, 2009 6:27 pm
by tr0gd0rr
Oh, this is a horrible, terrible, no good, very bad road to go down. You don't want to be using a template system that uses eval(). You'll be throwing out security and speed. There are tons of better and simpler templating systems out there.

http://www.google.com/search?q=php+template+system