【问题标题】:PHP: php and .html file separationPHP:php和.html文件分离
【发布时间】:2013-11-19 13:53:46
【问题描述】:

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

code.php

<?php
$data['#text#'] = 'A';

$html = file_get_contents('test.html');

echo $html = str_replace(array_keys($data),array_values($data),$html);
?>

test.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 放在 >

的中间

例如:&lt;div id="test"&gt; **aray_values here** &lt;/div&gt;

test.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;
    }
}

?>

test.html

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

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

所需输出:&lt;div id="test" &gt;A&lt;/div&gt;

【问题讨论】:

  • 使用 PHP 模板引擎 (smarty.net) 或按原样设置 PHP DOMDocument (php.net/manual/en/class.domdocument.php) 可能更容易。
  • 我不想使用任何第三方
  • 如果总是这样,您可以将id="test" &gt;&lt; 替换为id="test" &gt;VALUE&lt;。但我根本不会将自己与 HTML 结构联系在一起。在实践中,您可能需要输出的不仅仅是元素内部的值。有时您可能需要根据上下文添加额外的元素或元素的属性。
  • 好的,那么 DOMDocument 或(更随意的)str_replace() 或 preg_replace() 是选项。 DOMDocument->loadHTML(""),getElementById,更新值,DOMDocument->saveHTML。非第三方,自 PHP 4.1 起有效
  • 好主意,但我想弄清楚我刚开始是什么^_^

标签: php file-get-contents key-value array-key


【解决方案1】:

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

【讨论】:

  • 可以不使用函数吗?
  • 是的,但根据我的经验,该功能使调试变得更加容易。看看 php.net/preg_replace_callback,你也可以在类或对象中拥有该函数
【解决方案2】:

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

看到这个答案:What is phtml, and when should I use a .phtml extension rather than .php?

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

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 2017-11-14
    • 2021-09-25
    • 2017-06-29
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多