TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   preg_match and that stuff.. (http://www.talkphp.com/absolute-beginners/1787-preg_match-stuff.html)

Tanax 12-21-2007 04:49 PM

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??

sjaq 12-21-2007 06:47 PM

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)

Tanax 12-21-2007 07:13 PM

Quote:

Originally Posted by sjaq (Post 7022)
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 :)

sjaq 12-21-2007 07:18 PM

Quote:

Originally Posted by Tanax (Post 7023)
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);

?>


Tanax 12-21-2007 09:07 PM

Quote:

Originally Posted by sjaq (Post 7024)
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); 

???

sjaq 12-21-2007 09:46 PM

Quote:

Originally Posted by Tanax (Post 7032)
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..

Tanax 12-23-2007 02:17 PM

Quote:

Originally Posted by sjaq (Post 7043)
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..

Thanks! :-D

One thing that I noticed though.
Cause in my database, I have a table called posts, and wihin it, every row starts with "post_", for example:

Code:

post_content
post_author
post_time

And when I use like this in the template file:
HTML Code:

Posted at {post.post_time}
..it didn't work :-/

PHP Code:

foreach($posts as $post) {
                        
            
$tanaxia['template']->parse(
            
            array(
        
                
'post' => $post
                   
)
                   
            ));
            
        } 

$post will contain an array with all the data from the fetched rows.. so that should work :S

But it doesn't.

It works if I do like this:

PHP Code:

foreach($posts as $post) {
                        
            
$tanaxia['template']->parse(
            
            array(
        
                
'post' => array(
                    
                       
'posttime' => $post['post_time'],
                       
'postauthor' => $post['post_author'],
                       
'postcontent' => $post['post_content']
                   )
                   
            ));
            
        } 

HTML Code:

<center>

        <table width="900" border="1">

                <tr>

                        <td colspan="3"><font size="2">Posted {post.posttime}</font></td>

                </tr>
                       
                <tr>

                        <td colspan="2" width="30%">By: {post.postauthor}</td>
                        <td>{post.postcontent}</td>               

                </tr>
               
        </table>
       
</center>

Notice that I removed the _ from the template...
Any idea how to fix that ?? :-/:-/

xenon 12-23-2007 03:30 PM

Change this line:

PHP Code:

$replaced preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this'replace_callback'), $contents); 

to:

PHP Code:

$replaced preg_replace_callback('/\{([a-z0-9\._]+)\}/i', array($this'replace_callback'), $contents); 

</span></span>

Tanax 12-23-2007 03:58 PM

Quote:

Originally Posted by xenon (Post 7115)
Change this line:

PHP Code:

$replaced preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this'replace_callback'), $contents); 

to:

PHP Code:

$replaced preg_replace_callback('/\{([a-z0-9\._]+)\}/i', array($this'replace_callback'), $contents); 

</span></span>

Thanks xenon :D


All times are GMT. The time now is 10:54 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0