使用 preg_replace_callback 函数
$str = '#_1Testheadline#
#_2second headline under the first one
#_2another headline under the first one
#_1second headline (not under the first one)';
// Current level
$level = 0;
echo preg_replace_callback('/#?\s*#_(\d)+/',
function($x) use (&$level) {
// Close previous tag if it is
$out = ($level ? "</h{$level}>\n" : '');
// Save current level and open tag
$level = $x[1];
return $out . "<h{$level}>";
},
// Don't forget to close the last tag
$str) . "<h{$level}>";
结果
<h1>Testheadline#</h1>
<h2>second headline under the first one</h2>
<h2>another headline under the first one</h2>
<h1>second headline (not under the first one)<h1>
更新 1
您可以使用相同的方法来构建有序列表
$level = 0;
echo preg_replace_callback('/#?\s*#_(\d)+/',
function($x) use (&$level) {
if($x[1] > $level) $out = "\n<ol>\n";
else if ($x[1] < $level) $out = "</li>\n</ol>\n";
else $out = "</li>\n";
$level = $x[1];
return $out . "<li>";
},
$str) . "</li>\n</ol>\n";
结果
<ol>
<li>Testheadline#
<ol>
<li>second headline under the first one</li>
<li>another headline under the first one</li>
</ol>
<li>second headline (not under the first one)</li>
</ol>
更新 2
通过 css 样式化列表
<STYLE>
ol {
list-style: none;
counter-reset: li;
}
li:before {
counter-increment: li;
content: counters(li,".") ". ";
}
</STYLE>
<ol>
<li>Testheadline#
<ol>
<li>second headline under the first one</li>
<li>another headline under the first one</li>
</ol>
<li>second headline (not under the first one)</li>
</ol>
更新 3
用php进行编号
$cnts = [ 0 ];
echo preg_replace_callback('/#?\s*#_(\d)+/',
function($x) use (&$cnts) {
$level = $x[1]-1;
if($level < count($cnts)-1) $cnts = array_slice($cnts, 0, $level+1);
if (! isset($cnts[$level])) $cnts[$level] = 1;
else $cnts[$level]++;
$temp = array_slice($cnts, 0, $level+1);
return "\n" . implode('.', $temp) . ". ";
},
$str) ;
结果
1. Testheadline
1.1. second headline under the first one
1.2. another headline under the first one
2. second headline (not under the first one)