Jump to content

replace array key with val


doddsey_65

Recommended Posts

hi, im trying to replace an arrays key with its value. this is so i can display the html on the pages.

 

eg:

 

index.html

<title>{BOARD_TITLE}</title>

 

index.php

$template->replace(array(
    '{BOARD_TITLE}' => $settings['board_name']
    ));

 

template.php(template class)

function replace($array)
    {
        foreach ($array as $key => $val)
        {
            echo $key = $val;
        }
        return;
    }

 

however {BOARD_TITLE} does not get replaced with the value. where am i going wrong?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/225688-replace-array-key-with-val/
Share on other sites

ive gotten one step closer but its only replacing the first part of the array.

 

function replace($array, $file)
    {
        $file = 'html/'.$file.'.html';
        
        foreach ($array as $key => $val)
        {
            echo str_replace($key, $val, file_get_contents('./'.$this->template.$file));
        }
        return;
    }

 

$template->replace(array(
    '{BOARD_NAME}' => $settings['board_short_name'],
    '{PAGE_TITLE}' => $lang->index
    ), 'header');

 

{PAGE_TITLE} does not get replaced.

You can use array_flip() for that. If somehow you don't need that. How about this:

 

function replace ($array)
    {
        foreach ($array as $key => $val)
        {
            $array[$val] = $key;
            $array[$key] = NULL;
        }
        return $array;
    }

that doesnt seem to work since the html file isnt included anywhere.

ive tried again, thinking it was a loop i needed but now {BOARD_NAME} isnt even replaced:

 

function replace($array, $file)
    {
        if(!is_array($array))
        {
            die('template->replace: No Array Specified');
        }

        $file = 'html/'.$file.'.html';
        
        $replace = '';
        
        foreach ($array as $key => $val)
        {
            while($element = each($array))
            {
                $replace .= str_replace($element['key'], $element['val'], file_get_contents('./'.$this->template.$file));
            }
        }
        echo $replace;
    }

try

<?php
function replace($array, $file) {
        $file = 'html/'.$file.'.html';
        $file = file_get_contents('./'.$this->template.$file);
        foreach ($array as $key => $val) $file = str_replace($key, $val, $file);
        echo $file;
        return;
    }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.