Jump to content

Complicated preg_replace (php) for template tag parsing


Brentley_11

Recommended Posts

I am writing a template parsing engine and I came across the need to parse some very complicated tags.  Here is an example:

 

Input:

Before{{{test}}}After
{{{array[1]}}}
{{{object->bandana('banana')}}}

 

Output (If it worked):

Before<?php echo TemplateVars::getVar("test"); ?>After
<?php echo TemplateVars::getVar("array")[1]; ?>
<?php echo TemplateVars::getVar("object")->bandana('banana'); ?>

 

The php code I am using to parse this is:

$regex = '/[{]{3}([\w]+)([\-\[=>\W]*)([\w\(\'"]*)([\]\)]*)[}]{3}/U';
preg_replace($regex,'<?php echo TemplateVars::getVar("$1")$2$3$4; ?>',$data);

 

Unfortunately that outputs the following:

Before<?php echo TemplateVars::getVar("t")est; ?>After
<?php echo TemplateVars::getVar("array")[1]; ?>
<?php echo TemplateVars::getVar("object")->bandana('banana'); ?>

 

 

I have also tried stuff like:

$regex = '/[{]{3}([\w]+)([^}.]*)[}]{3}/U';

 

But that gives every tag the same results as {{{test}}}.

 

Any help is appreciated. Also if I need to elaborate more just ask.

Try:

<html><body><pre><?php

$content="Before{{{test}}}After\n{{{array[1]}}}\n{{{object->bandana('banana')}}}";

echo $content;

preg_match('/(\{{3})(\w+)(\}{3})(.*?)\s*\1(\w+)(\[\d+\])\3.*?\1(\w+)(->\w+\(\'\w+\'\))/s',$content,$matches);
echo "\n\n";
print_r($matches);

$output = <<<END
<?php echo TemplateVars::getVar("$matches[2]"); ?>$matches[4]
<?php echo TemplateVars::getVar("$matches[5]")$matches[6]; ?>
<?php echo TemplateVars::getVar("$matches[7]")$matches[8]; ?>
END;

echo htmlentities($output);

?>
</pre></body>
</html>

 

The only thing it doesn't match is the "Before," but if you're using preg_replace, not a problem, right?  If you do need to match that, let me know what it will look like, and I can add it.

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.