php自动生成标签,php – 根据标题标签自动生成嵌套的目录

哪位狡猾的程序员可以向我展示一个优雅的PHP编码解决方案,用于根据页面上的标题标签自动生成嵌套的目录?

所以我有一个html文件:

Animals

Some content goes here.

Some content goes here.

Mammals

Some content goes here.

Some content goes here.

Terrestrial Mammals

Some content goes here.

Some content goes here.

Marine Mammals

Some content goes here.

Some content goes here.

Whales

Some content goes here.

Some content goes here.

更具体地说,我想要一个链接的目录,其形式是在同一页面上的标题链接的嵌套列表:

目录(由PHP代码自动生成)

>动物

>哺乳动物

> Terrestrial_Mammals

> Marine_Mammals

>鲸鱼

解决方法:

我觉得它不优雅,但可能有助于大致了解如何创建一个;)

它使用simple_html_dom来查找和操作原始html中的元素

$htmlcode = <<< EOHTML

Animals

Some content goes here.

Some content goes here.

Mammals

Some content goes here.

Some content goes here.

Terrestrial Mammals

Some content goes here.

Some content goes here.

Marine Mammals

Some content goes here.

Some content goes here.

Whales

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 .= "

  1. ";

else{

$toc .= str_repeat('

', $last_level - $level);

$toc .= '';

}

$toc .= "

{$innerTEXT}";

$last_level = $level;

}

$toc .= str_repeat('

', $last_level);

$html_with_toc = $toc . "


" . $html->save();

标签:dynamically-generated,php

来源: https://codeday.me/bug/20190929/1830215.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值