I'm adding prefixes to headers in markdown using a script. For example, if I have:
# Hello
## World
### Let's add
## Some headers
### Yay!
# Foo
## Bar
I transform it to:
# 1 Hello
## 1.1 World
### 1.1.1 Let's add
## 1.2 Some headers
### 1.2.1 Yay!
# 2 Foo
## 2.1 Bar
I currently have the following working code, but it feels a bit hacky and prone for error. :
preg_match_all('/^(#+)\s(.*)$/m', $markdown, $headers);
$levelCount = [];
$currentLevel = 9999;
foreach ($headers[2] as $idx => $header) {
$level = strlen($headers[1][$idx]);
if ($level < $currentLevel) {
// reset:
for ($i = $level; $i != $currentLevel; $i += 1) {
array_pop($levelCount);
}
}
if (!isset($levelCount[$level])) {
$levelCount[$level] = 1;
} else {
$levelCount[$level] += 1;
}
$prefix = implode('.', array_values($levelCount));
$currentLevel = $level;
$markdown = preg_replace(
'/' . preg_quote($headers[0][$idx]) . '/',
$headers[1][$idx] . ' ' . $prefix . ' ' . $header,
$markdown,
1
);
}
What are your thoughts on this?