Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP删除.html文件的部分_Php_Html_Parsing - Fatal编程技术网

使用PHP删除.html文件的部分

使用PHP删除.html文件的部分,php,html,parsing,Php,Html,Parsing,我想编辑一个HTML页面。我想删除.html文件的某个部分,例如 <div id="gg"> ...... ...... </div> 我该怎么做 $file = file_get_contents("index.html"); $file = preg_replace('/<div id="gg">.*?<\/div>/im', '' $file); file_put_contents($file); 我没有测试这个代码 注意:嵌套的div破

我想编辑一个HTML页面。我想删除.html文件的某个部分,例如

<div id="gg">
......
......
</div>
我该怎么做

$file = file_get_contents("index.html");
$file = preg_replace('/<div id="gg">.*?<\/div>/im', '' $file);
file_put_contents($file);
我没有测试这个代码

注意:嵌套的div破坏了html结构

我没有测试这个代码


注意:嵌套的div破坏了html结构。

使用XML或html解析器可能会有些运气。for PHP5看起来非常易于使用,它提供了一种机制,可以通过ID查找特定元素,然后将其内容设置为空字符串。

使用XML或HTML解析器可能会有些运气。for PHP 5看起来非常易于使用,它提供了一种机制,可以通过ID查找特定元素,然后将其内容设置为空字符串。

我建议使用PHP的DOM库:

$dom = new DOMDocument;
$dom->loadHTML('<html string />'); // Or $dom->loadHTMLFile('file_name.html');

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[id="gg"]');
if($nodes->length)
  $nodes[0]->parentNode->removeChild($nodes[0]);

$dom->saveHTML(); // Or $dom->saveHTMLFile('file_name.html');

我建议使用PHP的DOM库:

$dom = new DOMDocument;
$dom->loadHTML('<html string />'); // Or $dom->loadHTMLFile('file_name.html');

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[id="gg"]');
if($nodes->length)
  $nodes[0]->parentNode->removeChild($nodes[0]);

$dom->saveHTML(); // Or $dom->saveHTMLFile('file_name.html');

你的意思是一次,或按请求和/或某些条件串行?你的意思是一次,或按请求和/或某些条件串行?请参阅:如果其中有嵌套的div,会发生什么?我知道,但在简单任务中,regex很好。嵌套的div break html。谢谢你的建议。看:如果有一个嵌套的div在那里会发生什么?我知道,但在简单的任务中,正则表达式是好的。嵌套的div break html。谢谢你的建议。