Jump to content

Help with 'preg_replace_callback'


Swift-R

Recommended Posts

Hello,

 

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

 

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:

 

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

echo $this->template ( $template_A );

 

This outputs:

 

<head></head><html></html>

 

And I want it to output:

 

<html><head></head></html>

 

What's the best way to fix this? :)

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/169604-help-with-preg_replace_callback/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.