tags:

views:

120

answers:

2

Hi everyone, I'm working on a simple templating system. Basically I'm setting it up such that a user would enter text populated with special tags of the form: <== variableName ==>

When the system would display the text it would search for all tags of the form mentioned and replace the variableName with its corresponding value from a database result.

I think this would require a regular expression but I'm really messed up in REGEX here. I'm using php btw.

Thanks for the help guys.

A: 

If you are doing a simple replace, then you don't need to use a regexp. You can just use str_replace() which is quicker.

(I'm assuming your '<== ' and ' ==>' are delimiting your template var and are replaced with your value?)

$subject = str_replace('<== '.$varName.' ==>', $varValue, $subject);

And to cycle through all your template vars...

$tplVars = array();
$tplVars['ONE'] = 'This is One';
$tplVars['TWO'] = 'This is Two';
// etc.

// $subject is your original document
foreach ($tplVars as $varName => $varValue) {
  $subject = str_replace('<== '.$varName.' ==>', $varValue, $subject);
}
w3d
Nice idea but the thing is that I don't want to run through my entire list of possible variables rather I wish to find and replace only those variables which do exist in the template.
Ali
+1  A: 

A rather quick and dirty hack here:

<?php

$teststring = "Hello <== tag ==>";

$values = array();

$values['tag'] = "world";


function replaceTag($name)
{
    global $values;
    return $values[$name];
}

echo preg_replace('/<== ([a-z]*) ==>/e','replaceTag(\'$1\')',$teststring);

Output:

Hello world

Simply place your 'variables' in the variable array and they will be replaced.

The e modifier to the regular expression tells it to eval the replacement, the [a-z] lets you name the "variables" using the characters a-z (you could use [a-z0-9] if you wanted to include numbers). Other than that its pretty much standard PHP.

Kristoffer S Hansen