代码
$content = '#### 内容
**A**: *B*
**C**: D
[下载 ](https://www.baidu.com?id=1 )';
preg_match_all('/.*?(\n|$)/', $content, $matches);
$rows = array_map(function ($line) {
$line = preg_replace('/\*\*(.*?)\*\*/', '<b>$1</b>', $line);//文字加粗
$line = preg_replace('/\*(.*?)\*/', '<i>$1</i>', $line);//斜体
if (preg_match('/^(#+)\s*(.*)/', $line, $match)) {//标题
$number = min(strlen($match[1]), 7);
return "<h{$number}>{$match[2]}</h{$number}>";
}
$line = preg_replace('/!\[(.*)\]\(\s*(\S+)\s*[\'"]?(.*?)[\'"]?\)/', '<img src="$2" alt="$1" title="$3" />', $line);//图片
$line = preg_replace('/\[(.*)\]\(\s*(\S+)\s*\)/', '<a href="$2" title="$1">$1</a>', $line);//链接
return "<p>{$line}</p>";
}, $matches[0] ?? []);
$html = implode(PHP_EOL, $rows);
效果如下
<h4>内容
</h4>
<p> <b>A</b>: <i>B</i>
</p>
<p> <b>C</b>: D
</p>
<p> <a href="https://www.baidu.com?id=1" title="下载 ">下载 </a></p>
<p></p>