变量未替换为file_get_contents()获取的字符串中的值

时间:2018-10-01 16:10:42

标签: php templates file-get-contents

我有一个文件,其中用定界符存储多个模板。我使用file_get_contents()获取内容,然后使用preg_match_all()解析它们。
在这些模板中,我包含变量,我希望它们会被它们的值替换,因为我使用大括号方法(可以在字符串中完成)(请参见下面的示例)。没有人有任何提示,为什么它不起作用?

code.tpl:

### CHAPTER_FILE_LIST START ###
<item id="{$CHAPTER['id']}" href="{$CHAPTER['file']}.xhtml" media-type="application/xhtml+xml"/>
### CHAPTER_FILE_LIST END ###

### CHAPTER_LIST START ###
<itemref idref="{$CHAPTER['id']}"/>
### CHAPTER_LIST END ###

PHP文件

function grab_templates() {
    global $tpl;
    if($raw_tpl = file_get_contents('templates/code.tpl')) {
        preg_match_all('/### ([A-Za-z._]+) START ###\s*([^#]+)### \1 END ###\s*/', $raw_tpl, $tpl_array);

        $count = count($tpl_array[1]);
        for($i = 0; $i < $count; $i++) {
            $tpl[$tpl_array[1][$i]] = $tpl_array[2][$i];
        }
    } else {
        echo 'Error getting code.tpl';
        exit;
    }
}

grab_templates();
$CHAPTER['id'] = 'name_of_chapter';
$CHAPTER['file'] = 'chapter_file';

echo $tpl['CHAPTER_FILE_LIST'].'<br />';
echo $tpl['CHAPTER_LIST'];

这应该定义模板变量:$tpl['CHAPTER_FILE_LIST']$tpl['CHAPTER_LIST']并输出:

<item id="name_of_chapter" href="chapter_file.xhtml" media-type="application/xhtml+xml"/>
<itemref idref="name_of_chapter"/>

但是它正在输出:

<item id="{$CHAPTER['id']}" href="{$CHAPTER['file']}.xhtml" media-type="application/xhtml+xml"/>
<itemref idref="{$CHAPTER['id']}"/>

1 个答案:

答案 0 :(得分:0)

您可以尝试修改代码。

在code.tpl中:

### CHAPTER_FILE_LIST START ###
<item id="[CHAPTER_ID]" href="[CHAPTER_FILE].xhtml" media-type="application/xhtml+xml"/>
### CHAPTER_FILE_LIST END ###

### CHAPTER_LIST START ###
<itemref idref="[CHAPTER_ID]"/>
### CHAPTER_LIST END ###

在您的PHP文件中:

$vars = array("[CHAPTER_ID]" => "name_of_chapter", "[CHAPTER_FILE]" => "chapter_file"); 

function grab_templates() {
    global $tpl;
    global $vars;
    if($raw_tpl = file_get_contents('templates/code.tpl')) {
        preg_match_all('/### ([A-Za-z._]+) START ###\s*([^#]+)### \1 END ###\s*/', $raw_tpl, $tpl_array);
        $count = count($tpl_array[1]);
        for($i = 0; $i < $count; $i++) {
            $tpl[$tpl_array[1][$i]] = str_replace(array_keys($vars), array_values($vars), $tpl_array[2][$i]);
        }
    } else {
        echo 'Error getting code.tpl';
        exit;
    }
}

grab_templates();
echo $tpl['CHAPTER_FILE_LIST'].'<br />';
echo $tpl['CHAPTER_LIST'];
相关问题