PHP:php和.html文件分离 [英] PHP: php and .html file separation

查看:477
本文介绍了PHP:php和.html文件分离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在分离HTML& PHP代码是我目前正在使用的代码.

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>

输出: A

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

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

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

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>

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

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

所需的输出:<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);
}

警告:代码未经测试,可以进行改进-重新设置全局关键字以及>和之间允许使用哪些项目

正则表达式说明:

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

这篇关于PHP:php和.html文件分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆