Jump to content

Regex question


phpscriptcoder

Recommended Posts

Hi,

I'm trying to make a simple templating system for use in another script. I want to have a feature to include another template file, but am not sure how.

This is what I am trying to use ($template is the contents of the template file).

 

$template = preg_replace('/\{\{([^\}]+)\}\}/', file_get_contents('\\\0'), $template);

 

It tries to include the file \\\0 rather than the correct filename.

 

This is supposed to match a string like {{header.html}} and replace it with the contents of the file within the braces.

 

I have tried some different methods, but none of them work.

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/110575-regex-question/
Share on other sites

Try using preg_replace_callback() if you want a function to be run before replacing content. preg_replace() takes strings as parameters - file_get_contents('\\\0') is not a string. Also, shouldn't you use "\\1" instead of "\\\0"?

 

<?php
function evaluate($matches) {
return file_get_contents($matches[1]);
}
$template = preg_replace_callback('/\{\{([^\}]+)\}\}/', 'evaluate', $template);
?>

Link to comment
https://forums.phpfreaks.com/topic/110575-regex-question/#findComment-567289
Share on other sites

Try using preg_replace_callback() if you want a function to be run before replacing content. preg_replace() takes strings as parameters - file_get_contents('\\\0') is not a string. Also, shouldn't you use "\\1" instead of "\\\0"?

 

<?php
function evaluate($matches) {
return file_get_contents($matches[1]);
}
$template = preg_replace_callback('/\{\{([^\}]+)\}\}/', 'evaluate', $template);
?>

 

Thanks, that worked.

Link to comment
https://forums.phpfreaks.com/topic/110575-regex-question/#findComment-567314
Share on other sites

Is it possible to pass additional arguments to the callback function?

 

My code for the templater so far:

<?php
function process_include($matches)
{
return templater(file_get_contents($matches[1]), $vars);
}
function templater($file, $vars)
{
$template = file_get_contents(templates.'/'.$file);
foreach($vars as $k => $v)
{
	$template = str_replace('[$'.$k.']', $v, $template);
}
$template = preg_replace_callback('/\{\{([^\}]+)\}\}/', 'process_include', $template);
echo $template;
}
?>

I am calling the templater function recursively so the additional template files will be processed as well. $vars is set in the file calling the templater, and I need to pass it every time the templater is called recursively. Any help?

Link to comment
https://forums.phpfreaks.com/topic/110575-regex-question/#findComment-567325
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.