www.webdeveloper.com
Results 1 to 7 of 7

Thread: Accessing Array Elements based on Strings

  1. #1
    Join Date
    Feb 2008
    Posts
    70

    Accessing Array Elements based on Strings

    Hello guys, I am trying to do a templating system and the way it works is taking values in brackets {tag} and then replacing them with the corresponding value in the $tag array.

    For example {user} will be replaced by $tag[user].

    So far so good...the problem i am having is when i try to replace tags in a multidimantional array.

    for example {user:name} should be replaced by $tag[user][name]
    and {user:addressostal_code} with $tag[user][address][postal_code]
    there is no limit to the depth.

    I am using the following code to do this (generate the '$tag[category][subcategory][...][...] as string and then using eval i get its value) and it works perfectly.
    BUT I do not like to use eval() because of security risks.

    Please suggest how I can avoid this.

    PHP Code:
    //Replace Template {tags} with values in the $tag array  - NEW    
            
    $match = array(); 

            
    preg_match_all('/\{(\w+|:)+?\}/'$render_page,$match);
            
            
    //Replace found {tags} with corresponding array values
            
    foreach($match[0] as $found_tag)
            {
                
    $view_tags[] = $found_tag
                
    $found_tag ltrim($found_tag,'{');
                
    $found_tag rtrim($found_tag,'}');
                
    $x explode(':',$found_tag);
                
                
    $x_tag '$tag_values[] = $tag';
                for(
    $i=0$i!=sizeof($x); $i++)
                {
                    
    $x_tag .= '['.$x[$i].']';
                }
                eval(
    "$x_tag;");
            }
            
    $render_page str_replace($view_tags$tag_values$render_page); 

  2. #2
    Join Date
    Aug 2009
    Posts
    593
    This is my little test, hope it gives you some ideas...

    PHP Code:
    $tag = array(
        
    'domain' => 'webdeveloper.com',
        
    'user'   => array(
            
    'name'    => 'thraddash',
            
    'address' => array(
                
    'postal_code' => '1234'
            
    )
        )
    );
    $template 'Hello {user:name} from {domain}, your postal code is {user:address:postal_code}, bye now {user:name}';

    if (
    preg_match_all('/\{([^}]+)\}/'$template$matches)) {
        
    $ref_template $template;
        for (
    $i 0$i count($matches[0]); $i++) {
            
    $ref_tag = &$tag;
            foreach (
    explode(':'$matches[1][$i]) as $part) {$ref_tag = &$ref_tag[$part];}
            
    $ref_template str_replace($matches[0][$i], '<b>' $ref_tag '</b>'$ref_template);
        }
        echo 
    $ref_template;


  3. #3
    Join Date
    Jul 2010
    Location
    /ramdisk/
    Posts
    865
    BUT I do not like to use eval() because of security risks.
    fine

    PHP Code:
    $you " might benefit from using a variable variable";
    $variable "you";

    echo 
    $variable, $$variable
    You could also use explode on the obvious delimiter, and work through it.
    Last edited by eval(BadCode); 12-28-2010 at 01:04 PM.
    I use (, ; : -) as I please- instead of learning the English language specification: I decided to learn Scheme and Java;

  4. #4
    Join Date
    Aug 2009
    Posts
    593
    I tried what eval(BadCode) suggested but couldn't get it right myself using multi-dimensional arrays...

    I made another version, it still uses eval but its a cool one line version instead

    PHP Code:
    $tag = array(
        
    'domain' => 'webdeveloper.com',
        
    'user'   => array(
            
    'name'    => 'thraddash',
            
    'address' => array(
                
    'postal_code' => '1234'
            
    )
        )
    );
    $template 'Hello {user:name} from {domain}, your postal code is {user:address:postal_code}, bye now {user:name}';

    echo 
    preg_replace('/\{([^}]+)\}/e''eval(\'return $tag[\\\'\'.implode(\'\\\'][\\\'\',explode(\':\',\'${1}\')).\'\\\'];\')'$template); 

  5. #5
    Join Date
    Feb 2008
    Posts
    70
    eval(BadCode)'s method was my first attempt to it as well, couldnt get it to work though.

    thraddash, thanx for the suggestions. I will try the first method and see what happens. I like the simplicity of the second method aswell but I really want to avoid using eval especially in this case because the "template" might also contain user input.

    I am a bit unclear on what this line does:
    $ref_tag = &$ref_tag[$part];

    can you explain?

  6. #6
    Join Date
    Aug 2009
    Posts
    593
    Quote Originally Posted by paishin View Post
    I am a bit unclear on what this line does:
    $ref_tag = &$ref_tag[$part];
    I am using references to the array members. &

    Initially you set the reference to the beginning of the array... $ref_tag = &$tag;

    Then I refer to itself to climb up to the required array member within the loop: $ref_tag = &$ref_tag[$part];

    You could do other checks at that point, like if that array member exists or if you stopped on an array instead of a value, and possibly return a default array member or string eg. {user:address} would output Array instead of something meaningful.

  7. #7
    Join Date
    Feb 2008
    Posts
    70
    thanks thraddash, it works perfectly!!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles