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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.