PHP如何正确替换页面中的元素?

时间:2014-03-25 22:05:48

标签: php

美好的一天。

我们的 test.php 包含下一个代码:

<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST1; ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST2; ?>" />
<div class="container">
<p class="test">{Text}</p>
</div>
<!-- STYLE_TEST1 and STYLE_TEST2 - set in define as "/css/styletest1.css" and "/css/styletest2.css" -->

index.php ,代码为:

$content = file_get_contents("test.php");
$content = ereg_replace("{Text}", 'hello', $content);
echo $content;

结果中我们得到代码:

<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST1; ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST2; ?>" />
<div class="container">
<p class="test">{Text}</p>
</div>

我们遇到样式问题,因为echo $content;打印<?php echo STYLE_TEST1; ?><?php echo STYLE_TEST2; ?>并且没有替换为这些元素定义的值(而不是更改&#34; / css / styletest1.css&#34;和&#34; /css/styletest2.css")。

请告诉我如何更换?

P.S。:我们需要将样式包含在文件test.php中,即文件 test.php 应该有行:

<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST1; ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST2; ?>" />

2 个答案:

答案 0 :(得分:1)

谢谢大家的帮助!

对我来说,这是我最好的决定

function getTemplate($file) {

    ob_start(); // start output buffer

    include $file;
    $template = ob_get_contents(); // get contents of buffer
    ob_end_clean();
    return $template;

}

$content = getTemplate("test.php");
$content = ereg_replace("{Text}", 'hello', $content);
echo $content;

答案 1 :(得分:0)

解决这个问题的一种方法是将其变为变量......

确保你有

define("STYLE_TEST1", "/css/styletest1.css");
define("STYLE_TEST2", "/css/styletest2.css");

<强> test.php的

<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST1; ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo STYLE_TEST2; ?>" />
<div class="container">
<p class="test">{<?=$variable?>}</p>
</div>
<!-- STYLE_TEST1 and STYLE_TEST2 - set in define as "/css/styletest1.css" and "/css/styletest2.css" -->

<强>的index.php

$variable = 'hello';

include 'test.php';

结果将是:

<link rel="stylesheet" type="text/css" href="/css/styletest1.css" />
<link rel="stylesheet" type="text/css" href="/css/styletest2.css" />
<div class="container">
<p class="test">{hello}</p>
</div>