TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 12-21-2007, 04:49 PM   #1 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default preg_match and that stuff..

Hey!

I don't know barely anything about this, and I want to create a simple template system where I would replace variables.

What I would want is like this:

HTML Code:
Hello and welcome {user.username}!
Your last visit was {user.lastvisit} here on {site.name}!
The "username" is the key in the "user" array.
So
HTML Code:
{user.lastvisit}
would fetch
PHP Code:
$user['lastvisit'
PHP Code:
$user = array();
$user['lastvisit'] = 'something';
$user['username'] = 'Tanax';

$site = array();
$site['name'] = 'TalkPHP';

$values = array();
$values[] = $user;
$values[] = $site;

$tpl->parse('index'$values); 
How would the function parse look like??
Tanax is offline  
Reply With Quote
Old 12-21-2007, 06:47 PM   #2 (permalink)
The Acquainted
 
sjaq's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 113
Thanks: 11
sjaq is on a distinguished road
Terminal

I tried it a couple of different ways but this seems to work fine:
Template.php
PHP Code:
<?php 

    
class Template
    
{
        public 
$data;
        const 
TEMPLATE_PATH './';
        
        public function 
parse($template, array $values)
        {
            
$this->data $values;
            if(!
file_exists(self::TEMPLATE_PATH $template '.php')) {
                die(
'Template file doesn\'t exist');
            } else {
                
$fb fopen(self::TEMPLATE_PATH $template '.php''r');
                
$contents fread($fbfilesize(self::TEMPLATE_PATH $template '.php'));
                
fclose($fb);
                
                
$replaced preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this'replace_callback'), $contents);
                
                print 
$replaced;
            }
        }
        
        private function 
replace_callback($matches
        {
            
$depth explode('.'$matches[1]);
            
$out $this->data;
            
            if(
count($depth) > 1) {
                foreach(
$depth as $ar) {
                    
$out $out[$ar];
                }
            } else {
                
$out $out[$depth[0]];
            }
            
            return 
$out;
        }
    }

?>
Test.php (the template)
Code:
Hello and welcome {user.username}!
Your last visit was {user.lastvisit} here on {site.name}!
Your postcount is: {user.posts.count}!
index.php
PHP Code:
<?php 

    
require './template.php';
    
    
$tpl = new Template;
    
    
$tpl->parse('test', array(
        
'user' => array(
            
'lastvisit' => 'yesterday',
            
'username' => 'Sjaq',
            
'posts' => array('count' => 10)
        ),
        
'site' => array(
            
'name' => 'TalkPHP'
        
)
    ));

?>
(My indentation style is a bit inconsistent, I'm trying to adapt the BSD/Allman style)

Last edited by sjaq : 12-21-2007 at 07:04 PM. Reason: uses fopen instead of file_get_contents now
sjaq is offline  
Reply With Quote
The Following User Says Thank You to sjaq For This Useful Post:
Tanax (12-21-2007)
Old 12-21-2007, 07:13 PM   #3 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Quote:
Originally Posted by sjaq View Post
I tried it a couple of different ways but this seems to work fine:
Template.php
PHP Code:
<?php 

    
class Template
    
{
        public 
$data;
        const 
TEMPLATE_PATH './';
        
        public function 
parse($template, array $values)
        {
            
$this->data $values;
            if(!
file_exists(self::TEMPLATE_PATH $template '.php')) {
                die(
'Template file doesn\'t exist');
            } else {
                
$fb fopen(self::TEMPLATE_PATH $template '.php''r');
                
$contents fread($fbfilesize(self::TEMPLATE_PATH $template '.php'));
                
fclose($fb);
                
                
$replaced preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this'replace_callback'), $contents);
                
                print 
$replaced;
            }
        }
        
        private function 
replace_callback($matches
        {
            
$depth explode('.'$matches[1]);
            
$out $this->data;
            
            if(
count($depth) > 1) {
                foreach(
$depth as $ar) {
                    
$out $out[$ar];
                }
            } else {
                
$out $out[$depth[0]];
            }
            
            return 
$out;
        }
    }

?>
Test.php (the template)
Code:
Hello and welcome {user.username}!
Your last visit was {user.lastvisit} here on {site.name}!
Your postcount is: {user.posts.count}!
index.php
PHP Code:
<?php 

    
require './template.php';
    
    
$tpl = new Template;
    
    
$tpl->parse('test', array(
        
'user' => array(
            
'lastvisit' => 'yesterday',
            
'username' => 'Sjaq',
            
'posts' => array('count' => 10)
        ),
        
'site' => array(
            
'name' => 'TalkPHP'
        
)
    ));

?>
(My indentation style is a bit inconsistent, I'm trying to adapt the BSD/Allman style)
Wow, thanks!! I will study the code more carefully :D

Also one thing, does this also work with variables?
Like if I do:

Code:
You are currently on page {page}
And that would be replaced with the value of
PHP Code:
$page 
???

THanks once again :)
Tanax is offline  
Reply With Quote
Old 12-21-2007, 07:18 PM   #4 (permalink)
The Acquainted
 
sjaq's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 113
Thanks: 11
sjaq is on a distinguished road
Default

Quote:
Originally Posted by Tanax View Post
Wow, thanks!! I will study the code more carefully :D

Also one thing, does this also work with variables?
Like if I do:

Code:
You are currently on page {page}
And that would be replaced with the value of
PHP Code:
$page 
???

THanks once again :)
No, it won't.

It gets all the data out of the array so if you would like to replace {page} with the contents of $page you'll have to do something like this:
PHP Code:
<?php 

    $values 
= array(
        
'page' => $page
    
);

    
$tpl->parse('test'$values);

?>
sjaq is offline  
Reply With Quote
The Following User Says Thank You to sjaq For This Useful Post:
Tanax (12-21-2007)
Old 12-21-2007, 09:07 PM   #5 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Quote:
Originally Posted by sjaq View Post
No, it won't.

It gets all the data out of the array so if you would like to replace {page} with the contents of $page you'll have to do something like this:
PHP Code:
<?php 

    $values 
= array(
        
'page' => $page
    
);

    
$tpl->parse('test'$values);

?>
Thanks! THat worked :D
Oh this is awesome ;)

Thanks a bunch!

Edit:
Can you explain this line?
PHP Code:
$replaced preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this'replace_callback'), $contents); 
???
Tanax is offline  
Reply With Quote
Old 12-21-2007, 09:46 PM   #6 (permalink)
The Acquainted
 
sjaq's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 113
Thanks: 11
sjaq is on a distinguished road
Book

Quote:
Originally Posted by Tanax View Post
Can you explain this line?
PHP Code:
$replaced preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this'replace_callback'), $contents); 
???
I'm assuming you understand regular expressions and I don't have to explain that part..

What that line does is that it searches for all occurrences of {([a-z0-9\.]+)} within the template file (which contents are in $contents) and then parses the matched string to $this->replace_callback.

Then the replace_callback method gets a string eg. "user.posts.count". It then "explodes" that string by each occurrence of "." so we get an array which looks something like this:
PHP Code:
Array
(
    [
0] => user
    
[1] => posts
    
[2] => count

And then it selects the correct data from the array(the second argument of the parse method) and returns it to the preg_replace_callback method, which in turn replaces the matched string by the returned data in the $contents string.

I recommend that you read the php site..
sjaq is offline  
Reply With Quote
The Following User Says Thank You to sjaq For This Useful Post:
Tanax (12-23-2007)
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 08:02 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design