PHP: php and .html file separation

霸气de小男生 提交于 2020-01-07 08:07:37

问题


I'm currently working on separating HTML & PHP code here's my code which is currently working for me.

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>

OUTPUT: A

it search and change the #text# value to array_value A it works for me.

Now i'm working on a code to search "id" tags on html file. If it's searches the "id" in ".html" file it will put the array_values in the middle of >

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

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>

My problem is I don't know how to put the array_values in the middle of every ></ search in the .html file.

Desired OUTPUT: <div id="test" >A</div>


回答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);
}

Warning: code is not tested and could be improved - re global keyword and what items are allowed between > and

Regular expression explanation:

(<([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



回答2:


Use views (.phtml) files to dynamically generate content. This is native for PHP (no 3rd party required).

See this answer: What is phtml, and when should I use a .phtml extension rather than .php?

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



来源:https://stackoverflow.com/questions/19844082/php-php-and-html-file-separation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!