You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Parsedown库生成Laravel内部链接时标题无ID问题

Hey there! Let's figure out why your ## New section isn't getting an ID attribute. The issue here is actually with the formatting of your input Markdown text—Parsedown (and most Markdown parsers) require headings to be on their own separate lines to be recognized as proper headings.

In your original code, you've got the headings directly tacked onto the end of list items without line breaks, so Parsedown isn't parsing them as headings at all. That's why no ID is generated for ## New section.

Fix 1: Correct your input Markdown format

Adjust your input text to put each heading on its own line, with a blank line separating the list from the headings (this is standard for Markdown block elements):

$Parsedown = new Parsedown();
$markdown = <<<MD
* [Hello](#hello)
* [Hello World](#hello-world)
* [Another section](#new-section)

## Hello

### Hello World

## New section
MD;
echo $Parsedown->text($markdown);

This will make Parsedown correctly identify each heading, generate the corresponding IDs (hello, hello-world, new-section), and your internal links will start working as expected.

Fix 2: Customize heading ID generation (if needed)

If you ever want to tweak how IDs are generated (like adding custom prefixes or handling special characters differently), you can extend Parsedown to override the heading handling logic. Here's a quick example:

class CustomParsedown extends Parsedown
{
    protected function blockHeading($Line)
    {
        $heading = parent::blockHeading($Line);
        if (isset($heading['element']['attributes']['id'])) {
            // Modify the ID here—e.g., add a "section-" prefix
            $heading['element']['attributes']['id'] = 'section-' . $heading['element']['attributes']['id'];
        }
        return $heading;
    }
}

$Parsedown = new CustomParsedown();
// Use the corrected Markdown from Fix 1 above
echo $Parsedown->text($markdown);

This would generate IDs like section-hello instead of just hello.

The core problem in your original code was the missing line breaks—fixing that will get your internal links working right away!

内容的提问来源于stack exchange,提问作者DolDurma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:05:28