在更改内部值的同时插入文件内容

时间:2020-02-20 05:39:23

标签: php

$title = '';

function insert($file){
    global $title;    
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;
}

abc.php

<div class='title'><?php echo $title; ?></div>

因此,我需要在更改内部变量时插入abc.php

在上面的(简化的)示例中,我期望结果为lorem ipsum,但我得到的是空div .title

2 个答案:

答案 0 :(得分:2)

根据您当前的流量,它不起作用。

尝试在当前文件中使用str_replace,并在abc.php文件中声明一个像#TITLE#这样的关键字

$title = '';

function insert($file){
    global $title;    
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;
}

abc.php

<div class='title'>#TITLE#</div>

希望这项工作对您有用。

答案 1 :(得分:1)

<?php
$template = "<div class='title'>%s</div>";

echo sprintf($template, 'this is title1');
echo sprintf($template, 'this is title2');

使用preg_replace或更具可读性的HTML模板:

PHP代码:

$body = file_get_contents('template.html');
$patterns = array(
  '/{title}/'
);
$replacements = array(
  'this is title',
);
$body = preg_replace($patterns, $replacements, $body);

template.html:

<div class='title'>{title}</div>
相关问题