用 html 标签和动态 class 名称替换定制的 BBCode 风格的开始代码标签

Replace customized BBCode-style opening code tags with html tags and a dynamic class name

我想用正则表达式替换一些单词。

我的话

[code-html(or css,js)]

html 是可变的。 我想这样替换

<pre><code class="language-html(or css,js)">

如何使用正则表达式替换所有变量?

我只能更换一个箱子

preg_match_all("/\[code-([a-zA-Z0-9]+)\]/", "<pre><code class=\"([a-zA-Z0-9]+)\]\">", $matches);

这是一个简单的解决方案,它要求您的起始代码标签具有语言子字符串并捕获它以便在替换字符串中重复使用。

这里是三个基本案例...

代码:(Demo)

$inputs = [
    '[code-html]',
    '[code-css]',
    '[code-js]',
];

var_export(
    preg_replace(
        '~\[code-(html|css|js)]~',
        '<pre><code class="language-">',
        $inputs
    )
);

输出:

array (
  0 => '<pre><code class="language-html">',
  1 => '<pre><code class="language-css">',
  2 => '<pre><code class="language-js">',
)