开发者

Need to extract special tags and replace them based upon their contents using regular expression

开发者 https://www.devze.com 2023-01-11 21:03 出处:网络
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 ==>

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 reall开发者_StackOverflow中文版y messed up in REGEX here. I'm using php btw.

Thanks for the help guys.


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.


Very useful - Pointed me to what I was looking for...

Replacing tags in a template e.g.

<<page_title>>, <<meta_description>>

with corresponding request variables e,g,

$_REQUEST['page_title'], $_REQUEST['meta_description'],

using a modified version of the code posted:

$html_output=preg_replace('/<<(\w+)>>/e', '$_REQUEST[\'$1\']', $template);

Easy to change this to replace template tags with values from a DB etc...


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消