Hello forums !!
I have some file named "test.tpl"
whic has following contents
"Hello %name% your passwrod is %passwrod%"
I would like to call this file and replace those values within % with dynamic values(may also {}).
Any comments and suggestions are warmly welcome.
Thanks in advance to all of you
how to parse template file ??
Moderator: General Moderators
- stereofrog
- Forum Contributor
- Posts: 386
- Joined: Mon Dec 04, 2006 6:10 am
Some Food for thought..
Very Basic Finds all matches of %Words% Then Trys and Replaces Whats in the Array $Replace.
Code: Select all
$Replace = array();
$Replace['age'] = '20';
$Replace['person'] = 'Jimmy (%age%)';
$Page = 'hi %person% whats up';
// Keeps Looping So if Replaced Vars have Matches it replaces those also: like %age%
while(preg_match_all('/' . '%' . '((\w?)+)' . '%' . '/',$Page,$Matches)){
$Matches = $Matches[1];
foreach($Matches as $Match){
// Replace No Matches So we Dont Keep Looping
$Replace[$Match] = !empty($Replace[$Match])? $Replace[$Match] : '';
$Page = str_replace('%' . $Match . '%',$Replace[$Match],$Page);
}
}
echo $Page;
// Echos -
// hi Jimmy (20) whats up
Better Yet..
(These are Just Small Examples, and Should be for Referencing only, there are other precautions you should take.)
(These are Just Small Examples, and Should be for Referencing only, there are other precautions you should take.)
Code: Select all
/**
* Kyle Wascher - kyle at zoxive.com
*/
class template{
/**
* Page String
* @var string
* @access protected
*/
protected $Page = NULL;
/**
* Replace Variables In an array
* @var array
* @access protected
*/
protected $Replace = array();
/**
* Takes Input $Page as String
*
* @param $Page String
* @return None Can not return Construct Functions
*/
public function __construct($Page){
$this->Page = $Page;
}
/**
* Replaces All Variables In $Page
*
* @return boolean
*/
public function doReplace(){
// Keeps Looping So if Replaced Vars have Matches it replaces those also: like %age%
while(preg_match_all('/' . '%' . '((\w?)+)' . '%' . '/',$this->Page,$Matches)){
$Matches = $Matches[1];
foreach($Matches as $Match){
// Replace No Matches So we Dont Keep Looping
$this->Replace[$Match] = !empty($this->Replace[$Match])? $this->Replace[$Match] : '';
$this->Page = str_replace('%' . $Match . '%',$this->Replace[$Match],$this->Page);
}
}
return true;
}
/**
* Sets Replace Array
*
* @return boolean
*/
public function __set($name,$var){
$this->Replace[$name] = $var;
return true;
}
/**
* Return Replace Var
*
* @return mixed - String or false
*/
public function __get($name){
return isset($this->Replace[$name])? $this->Replace[$name] : false;
}
/**
* Returns/Prints Page
*
* @param $show Boolean to return or print
* @return $Page or echo
*/
public function doPrint($show=true){
$this->doReplace();
if($show){
echo $this->Page;
}else{
return $this->Page;
}
}
}
$String = 'hi %person% whats up';
$Page = new template($String);
$Page->person = 'Jimmy (%age%)';
$Page->age = '20';
$Page->doPrint();