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 02: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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.14875 seconds
  • Memory Usage 2,921KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (4)bbcode_php
  • (2)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (7)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (7)postbit
  • (7)postbit_onlinestatus
  • (7)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates