PHP:php和.html文件分离


PHP: php and .html file separation

我目前正在研究分离HTML和PHP代码,这是我的代码,目前正在为我工作。

代码.php

<?php
$data['#text#'] = 'A';
$html = file_get_contents('test.html');
echo $html = str_replace(array_keys($data),array_values($data),$html);
?>

测试.html

<html>
<head>
<title>TEST HTML</title>
</head>
<body>
<h1>#text#</h1>
</body>
</html>

输出:A

它搜索并将 #text# 值更改为 array_value A 它对我有用。

现在我正在研究一个代码来搜索 html 文件上的"id"标签。如果它搜索".html"文件中的"id",它将把array_values放在中间>

例如:<div id="test"> **aray_values here** </div>

测试.php

<?php
$data['id="test"'] = 'A';
$html = file_get_contents('test.html');
foreach ($data as $search => $value)
{
    if (strpos($html , $search))
    {
        echo 'FOUND';
        echo $value;
    }
}
?>

测试.html

<html>
<head>
<title>TEST</title>
</head>
<body>
<div id="test" ></div>
</body>
</html>

我的问题是我不知道如何将array_values放在.html文件中每个></搜索的中间。

期望输出:<div id="test" >A</div>

function callbackInsert($matches)
{
    global $data;
    return $matches[1].$matches[3].$matches[4].$data[$matches[3]].$matches[6];
}

$data['test'] = 'A';
$html = file_get_contents('test.html');
foreach ($data as $search => $value)
{
    preg_replace_callback('#(<([a-zA-Z]+)[^>]*id=")(.*?)("[^>]*>)([^<]*?)(</''2>)#ism', 'callbackInsert', $html);
}

警告:代码未经测试,可以改进 - re全局关键字以及>和之间允许的项目

正则表达式说明:

(<([a-zA-Z]+) - any html tag starting including the last letter of the tag
[^>]* - anything that is inside a tag <>
id=")(.*?)(" - the id attribute and its value
[^>]* - anything that is inside a tag <>
>) - the closing tag
([^<]*?) - anything that is not a tag, tested by opening a tag <
(</''2>) - the closing tag matching the 2nd bracket, ie. the matching opening tag

使用视图 (.phtml) 文件动态生成内容。这是 PHP 的原生版本(不需要第三方)。

请参阅此答案:什么是 phtml,何时应该使用 .phtml 扩展名而不是 .php?

而这个:https://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html