gpt4 book ai didi

php - Markdown 中的自动命名 anchor

转载 作者:可可西里 更新时间:2023-11-01 00:48:29 27 4
gpt4 key购买 nike

我在 PHP 中使用 Markdown,并编写了一个正则表达式来自动将文本包装在里面(如果有的话)<h1>-<h6>带有命名 anchor ( <a name="Text">Text</a> ) 的标签用于链接。

这是 PHP:

$text = '<p>This is a</p>
<h1>Test</h1>
<p>to see if this works </p>';

$regex = '/\<h([0-6]{1})\>(.+)\<\/h[0-6]{1}\>/';

echo preg_replace($regex, '<h$1><a name="$2">$2</a></h$1>', $text);

结果是:

<p>This is a</p>
<h1><a name="Test">Test</a></h1>
<p>to see if this works </p>

这里重要的是,Markdown 重量轻且易于存储空间。手动添加命名 anchor 违背了完全使用 Markdown 的目的。

这种方法可以很好地用于测试目的,但我想知道(这是问题所在)是否有更好的、更语言无关的方法来完成这个。

注意:这是针对客户的,他们希望这样,因为他们觉得即使是原生 Markdown 语法也可能疏远他们更多的“计算机文盲”用户:# [Text](#Text) .他们只想输入:# Text

最佳答案

鉴于您已经在使用 PHP,您真的应该看看 Markdown Extra执行。来自 MDE 文档:

With PHP Markdown Extra, you can set id attribute to headers. You should add the id prefixed by a hash inside curly brackets after the header at the end of the line, like this:

Header 1            {#header1}
========

## Header 2 ## {#header2}

Then you can create links to different parts of the same document like this:

[Link back to header 1](#header1)

关于php - Markdown 中的自动命名 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12629366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com