输入数组,其中包含 WordPress 帖子中的 html 标题
<?php
$headings = array(
0 => "<h2>Number One</h2>",
1 => "<h2>Number Two</h2>",
2 => "<h2>Number Three</h2>",
3 => "<h3>Number Four</h3>",
4 => "<h2 id='iamanexistingid'>Number Five</h2>",
5 => "<h3>Number Six</h4>",
6 => "<h4>Number Seven</h2>",
7 => "<h2>Number Eight</h2>"
);
现在我想在嵌套无序列表中生成一个结构。
输出
<ul>
<li>Number One</li>
<li>Number Two</li>
<li>Number Three
<ul>
<li>Number Four</li>
</ul>
<li>Number Five</li>
<li>Number Five
<ul>
<li>Number Six
<ul>
<li>Number Seven</li>
</ul>
</li>
</ul>
</li>
<li>Number Eight</li>
</ul>
有没有简单的方法可以使用 Simple HTML DOM Parser 生成它?还是诡计?
我最初的解决方案对于比一级更深的级别实际上不起作用,并且总体来说不好。我也不知道如何处理 H3 之后的 H4 或 H3 之后的 H3。
<?php
$headings = array(
0 => "<h2>H2 Number One</h2>",
1 => "<h2>H2 Number Two</h2>",
2 => "<h2>H2 Number Three</h2>",
3 => "<h3>H3 Number Four</h3>",
4 => "<h2 id='iamanexistingid'>H2 Number Five</h2>",
5 => "<h3>H3 Number Six</h4>",
6 => "<h4>H4 Number Seven</h2>",
7 => "<h3>H3 Number Eight</h2>",
8 => "<h2>H2 Number Nine</h2>"
);
$array = array();
$lastlevel = 2;
foreach ($headings as $key => $value) {
preg_match("/\<(?<name>\w+)(?<attributes>\s+[^>]*|)>/", $value, $matches);
$tagname = $matches[1];
$currentlevel = str_replace("h", "", "$tagname");
if($currentlevel == $lastlevel OR $currentlevel < $lastlevel) {
array_push($array, $value);
} elseif ($currentlevel > $lastlevel) {
array_push($array, [$value]);
}
$lastlevel = $currentlevel;
}
echo printArrayList($array);
function printArrayList($array)
{
echo "<ul>";
foreach($array as $k => $v) {
if (is_array($v)) {
printArrayList($v);
continue;
}
echo "<li>" . $v . "</li>";
}
echo "</ul>";
}
拉莫斯之舞
相关分类