设置:
我有一个标准 .php 文件 (index.php),其中包含两个包含内容,一个用于页眉 (header.php),一个用于页脚 (footer.php)。 index.php 文件如下所示:
索引.php
<?php
include header.php;
?>
<h2>Hello</h2>
<p class="editable">Lorem ipsum dolar doo dah day</p>
<?php
include footer.php;
?>
header.php 像这样:
<html>
<head>
<title>This is my page</title>
</head>
<body>
<h1 class="editable">My Website rocks</h1>
和页脚 .php 像这样:
<p>The end of my page</p>
</body>
我正在编写一个 PHP 脚本,允许您编辑页面上的任何“.editable”项目。我的问题是这些可编辑区域可能出现在任何包含的文件以及index.php 的主体中。
我的 php 代码正在使用 file_get_contents() 获取 index.php 文件;效果很好。我还可以编辑和保存 index.php 中的任何“.editable”区域。
我的问题:
我一直无法找到一种方法来“查找”包含内容并解析“.editable”区域的内容。我正在寻找有关如何处理 index.php 中所有包含内容的建议 - 检查它们是否有可编辑区域。我需要使用正则表达式来查找“include *.php”吗?我什至不知道从哪里开始......
对于那些可能希望查看我的 PHP 代码的人。我正在使用 PHP 类:[链接文本][1],它允许我编写如下代码:
// load the class and file
$html = new simple_html_dom();
$html->load_file("index.php");
// find the first editable area and change its content to "edited"
$html->find('*[class*=editable]', 0)->innertext = "Edited";
// save the file
$html->save(index.php);
[1]: http://simplehtmldom.sourceforge.net/manual_api.htm http://simplehtmldom.sourceforge.net/manual_api.htm 简单的 php dom 解析器
UPDATE
我一直在尝试使用正则表达式来尝试匹配包含的内容。我对正则表达式很垃圾,但我想我已经很接近了。这是我到目前为止所拥有的:
$findinclude = '/(?:include|include_once|require|require_once)\s*(?:[a-z]|"|\(|\)|\'|_|\.|\s|\/)*(?=(?:[^\<\?]|[^\?\>])*\?>)/i';
尽管在使用 preg_match 时它似乎返回奇数 ) 和 ' ,但它匹配得相当好。我试图在正则表达式中添加一些安全性,以确保它只在 php 标签之间匹配 - 这部分: (?=(?:[^\])*\?>) - 但它只返回页面上的第一个包含内容。关于如何改进这个正则表达式有什么建议吗? (我已经花了大约6个小时)