mirror of
https://codeberg.org/PostERG/xamxam.git
synced 2026-08-10 15:21:22 +02:00
36 lines
1.0 KiB
PHP
36 lines
1.0 KiB
PHP
<?php
|
||
|
||
/**
|
||
* Shared markdown utilities.
|
||
*/
|
||
class MarkdownHelper
|
||
{
|
||
/**
|
||
* Extract h1–h3 headings from raw markdown content as TOC items.
|
||
*
|
||
* Each heading gets an anchor id matching CommonMark's default slugification
|
||
* (lowercase, spaces → hyphens, punctuation stripped).
|
||
*
|
||
* @return array<int, array{label: string, href: string, level: int}>
|
||
*/
|
||
public static function extractToc(string $content): array
|
||
{
|
||
$items = [];
|
||
$lines = explode("\n", $content);
|
||
|
||
|
||
// Use CommonMark's own SlugNormalizer so TOC links match the rendered heading IDs exactly.
|
||
$normalizer = new \League\CommonMark\Normalizer\SlugNormalizer();
|
||
|
||
foreach ($lines as $line) {
|
||
if (preg_match('/^(#{1,3})\s+(.+)$/', $line, $m)) {
|
||
$level = strlen($m[1]);
|
||
$label = trim($m[2]);
|
||
$id = $normalizer->normalize($label);
|
||
$items[] = ['label' => $label, 'href' => '#' . $id, 'level' => $level];
|
||
}
|
||
}
|
||
return $items;
|
||
}
|
||
}
|