php – 根据标题标签自动生成嵌套的目录
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 根据标题标签自动生成嵌套的目录,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1754字,纯文字阅读大概需要3分钟。
内容图文
![php – 根据标题标签自动生成嵌套的目录](/upload/InfoBanner/zyjiaocheng/707/077065e03afd4afa91a8bdb558ef5345.jpg)
哪位狡猾的程序员可以向我展示一个优雅的PHP编码解决方案,用于根据页面上的标题标签自动生成嵌套的目录?
所以我有一个html文件:
<h1> Animals </h1>
Some content goes here.
Some content goes here.
<h2> Mammals </h2>
Some content goes here.
Some content goes here.
<h3> Terrestrial Mammals </h3>
Some content goes here.
Some content goes here.
<h3> Marine Mammals </h3>
Some content goes here.
Some content goes here.
<h4> Whales </h4>
Some content goes here.
Some content goes here.
更具体地说,我想要一个链接的目录,其形式是在同一页面上的标题链接的嵌套列表:
目录(由PHP代码自动生成)
>动物
>哺乳动物
> Terrestrial_Mammals
> Marine_Mammals
>鲸鱼
解决方法:
我觉得它不优雅,但可能有助于大致了解如何创建一个;)
它使用simple_html_dom来查找和操作原始html中的元素
$htmlcode = <<< EOHTML
<h1> Animals </h1>
Some content goes here.
Some content goes here.
<h2> Mammals </h2>
Some content goes here.
Some content goes here.
<h3> Terrestrial Mammals </h3>
Some content goes here.
Some content goes here.
<h3> Marine Mammals </h3>
Some content goes here.
Some content goes here.
<h4> Whales </h4>
Some content goes here.
Some content goes here.
EOHTML;
// simpehtmldom or other dom manipulating library
require_once 'simple_html_dom.php';
$html = str_get_html($htmlcode);
$toc = '';
$last_level = 0;
foreach($html->find('h1,h2,h3,h4,h5,h6') as $h){
$innerTEXT = trim($h->innertext);
$id = str_replace(' ','_',$innerTEXT);
$h->id= $id; // add id attribute so we can jump to this element
$level = intval($h->tag[1]);
if($level > $last_level)
$toc .= "<ol>";
else{
$toc .= str_repeat('</li></ol>', $last_level - $level);
$toc .= '</li>';
}
$toc .= "<li><a href='#{$id}'>{$innerTEXT}</a>";
$last_level = $level;
}
$toc .= str_repeat('</li></ol>', $last_level);
$html_with_toc = $toc . "<hr>" . $html->save();
内容总结
以上是互联网集市为您收集整理的php – 根据标题标签自动生成嵌套的目录全部内容,希望文章能够帮你解决php – 根据标题标签自动生成嵌套的目录所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。