Re: Re: replacing variables in file
| From: | Rouvas Stathis | Date: | Sun, 12 Aug 2001 13:13:31 +0000 |
| Subject: | Re: Re: replacing variables in file | ||
| References: | 1 2 3 4 5 6 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-62304@lists.php.net to get a copy of this message | ||
Here is my solution :
function substitute($str,$lv) {
//
// recursively substitute all occurences of pattern !!var!! in $str
with $lv['var']
// could be done wiht a loop, but since circular references are not
resolved
// it is better to leave it that way. in case of a circular reference,
// eventually will run out of stack and indication of error will be
given
// if it is placed in loop, maybe it will never end:-)
//
$act = -1;
preg_match_all("/!!.*!!/U",$str,$tmpar); $act = count($tmpar[0]);
reset($tmpar[0]);
while (list($k,$v)=each($tmpar[0]))
$str = ereg_replace($v,$lv[strtolower(trim(ereg_replace('!','
',$v)))],$str);
if ($act > 0)
return substitute($str,$lv);
else
return $str;
}
Suppose you have the file foo.txt as in :
<foo.txt>
Dear !!name!!,
I have the !!item!! you requested at !!date!!
blah, blah, blah,
!!greets!!
</foo.txt>
In your code you do:
<?php
$txt = file('foo.txt');
$lv['name'] = 'Rouvas Stathis';
$lv['item'] = 'Code Snippet';
$lb['data'] = 'the other day';
$lv['greets'] = 'Bye';
$txt_new = substitute($txt,$lv);
echo $txt_new;
// you can have nested calls as in
$lv['first'] = 'Stathis';
$lv['last'] = 'Rouvas';
$lv['name'] = '!!first!! !!last!!';
$txt2 = substitute($txt,$lv);
echo $txt2;
?>
Hope it helps.
-Stathis.
Paul Roberts wrote:
>
> I want to read the include file in, replace the variables with any data
> present and then send the included file to the browser between some header
> and footer templates. I want the template to be straight html which can be
> edited with a wysiwyg editor if required.
>
> if I include the file as html I get errors as there are " and no valid
> syntax I my php block ie no ;
>
> i'd like to just do
>
> $formdata = (include($filelocation));
>
> but this returns 1 and pts it in the variable, I need the html form in the
> variable.