gpt4 book ai didi

php - 在php中制作H2-H3元素列表

转载 作者:行者123 更新时间:2023-11-27 23:22:45 25 4
gpt4 key购买 nike

我有一个 PHP 变量和我页面的 HTML 代码,它只包含段落和 H2-H3 元素:

<h2>Header 1</h2>

<p>Some text</p>
...
<p>Some text</p>

<h3>Sub-header 1</h3>

<p>Some text</p>
...
<p>Some text</p>

<h2>Header 2</h2>

我正在尝试创建一个函数,它接受一个带有 HTML 代码的变量并返回一个带有 HTML ul 列表的字符串:

<ul>
<li>Header 1
<ul>
<li>Sub-header 1</li>
</ul>
</li>
<li>Header 2
<ul>
<li>Sub-header 2</li>
<li>Sub-header 3</li>
</ul>
</li>
<li>Header 3</li>
</ul>

这是我取得的成就,但我坚持检测何时添加 sub-ul 标签以及如何添加:

function generate_navigation($HTML) {
$DOM = new DOMDocument();
$DOM->loadHTML($HTML);

$navigation = '<ul>';

// Iterating through all elements
$h2Iterator = 0;
foreach($DOM->getElementsByTagName('*') as $element) {
if($element->tagName == 'h2') {
$h2Iterator++;
$navigation .= '<li>' . $element->textContent . '</li>';
} else if ($element->tagName == 'h3') {
// How to add?
}
}

return $navigation.'</ul>';
}

最佳答案

您需要跟踪打开的 h2 标签。不需要迭代器计数器,但需要迭代器状态。

function generate_navigation($HTML) {
$DOM = new DOMDocument();
$DOM->loadHTML($HTML);

$navigation = '<ul>';

// Iterating through all elements
$h2IteratorStatus = 0; //0-closed, 1-open
$h3IteratorStatus = 0; //0-closed, 1-open
foreach($DOM->getElementsByTagName('*') as $element) {
if($element->tagName == 'h2') {

if($h3IteratorStatus){
//it's open, need to close
$navigation .= '</ul>';
$h3IteratorStatus = 0;
}

if($h2IteratorStatus){
//it's open, need to close
$navigation .= '</li>';
$h2IteratorStatus = 0;
}

$h2IteratorStatus = 1;
$navigation .= '<li>' . $element->textContent ;

} else if ($element->tagName == 'h3') {

if(!$h3IteratorStatus){
$navigation .= '<ul>';
$h3IteratorStatus = 1;
}

$navigation .= '<li>' . $element->textContent .'</li>';
}
}

//check for last opened h3
if($h3IteratorStatus){
$navigation .= '</ul>';
}
//check for last opened h2
if($h2IteratorStatus){
//it's open, need to close
$navigation .= '</li>';
}

return $navigation.'</ul>';
}

根据您的评论进行更新,以跟踪打开的 h3 标签。

关于php - 在php中制作H2-H3元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40241975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com