- preg_replace_callback: documentation ( source)
- array_slice: documentation ( source)
- implode: documentation ( source)
<?php
$headers = <<<HEADERS
# Hello
## World
### Let's add
## Some headers
### Yay!
# Foo
## Bar
## Bar Again
HEADERS;
$levels = [];
echo preg_replace_callback(
'~^(#+)\K~m',
function($m) use (&$levels) {
$hashes = strlen($m[1]);
$index = $hashes - 1;
$reduction = sizeof($levels) - $hashes;
if (!isset($levels[$index])) {
$levels[$index] = 1;
} else {
++$levels[$index];
}
if ($reduction > 0) {
$levels = array_slice($levels, 0, -$reduction);
}
return " " . implode('.', $levels);
},
$headers
);