用 <p> 替换 Heading (<h1>, <h2> ...) 标签标签和类

问题描述:

我希望将 WYSIWYG 编辑器中的标签替换为 .

I wish to replace tags from a WYSIWYG editor to .

目前我正在使用以下代码来实现这一点.

At the moment I am using the following code to achieve this.

$content = preg_replace('/<h1(.*?)<\/h1>/si', '<p class="heading-1"$1</p>', $content);
$content = preg_replace('/<h2(.*?)<\/h2>/si', '<p class="heading-2"$1</p>', $content);
$content = preg_replace('/<h3(.*?)<\/h3>/si', '<p class="heading-3"$1</p>', $content);
$content = preg_replace('/<h4(.*?)<\/h4>/si', '<p class="heading-4"$1</p>', $content);
$content = preg_replace('/<h5(.*?)<\/h5>/si', '<p class="heading-5"$1</p>', $content);
$content = preg_replace('/<h6(.*?)<\/h6>/si', '<p class="heading-6"$1</p>', $content);

如您所见,这段代码非常混乱,如果我能将其压缩为一个正则表达式就好了,但我只是缺乏这样做的能力.

As you can see this code is quite messy, it would be great if I could condense this into a single regular expression but I simply lack the ability to do so.

我曾考虑将这行代码作为替代方案.

I had considered this line of code as an alternative.

$content = preg_replace('/<h(.*?)<\/h(.*?)>/si', '<p class="heading-$2"$1</p>', $content);

我不确定是否使用上述内容,客户倾向于从其他网站复制内容,将其直接粘贴到他们的新 WYSIWYG 中,我看到从 hr 标签到标题标签的任何内容都出现在那里.

I'm not sure about using the above, clients have a tendency to copy content from other sites, paste it straight into their new WYSIWYG and i've seen anything from hr tags to heading tags popping in there.

我需要的只是上面的单行,除了标签本身只能是 2 个特定字符(因此请确保标签以 H 开头,后跟 [1-6]).

What I require is simply the above single line, except the tag itself can only be 2 specific characters (So ensure the tag starts with a H and is followed by [1-6]).

我还要求它添加到 p 标签的类是特定于数字使用的,例如:heading-1、heading-2.

I also require that the class it adds to the p tag is specific to the number use, eg: heading-1, heading-2.

非常感谢您的帮助,感谢您的时间.

Any help would be greatly appreciated, thank you for your time.

$content = <<<HTML
<h1 class="heading-title">test1</h1>
<H2 class="green">test2</H2>
<h5 class="red">test</h5>
<h5 class="">test test</h5>
HTML;

$content = preg_replace('#<h([1-6]).*?class="(.*?)".*?>(.*?)<\/h[1-6]>#si', '<p class="heading-${1} ${2}">${3}</p>', $content);

echo htmlentities($content);

结果:

<p class="heading-1 heading-title">test1</p> 
<p class="heading-2 green">test2</p> 
<p class="heading-5 red">test</p> 
<p class="heading-5 ">test test</p>

现有课程的注意事项:即使您的元素没有现有的类,您也必须添加空的类属性 class="".相反,这不会按预期工作.:( 更好的解决方案是使用 preg_replace_callback.然后您可以检查是否存在匹配项并更准确地创建您的 p 标签.

Note for existing classes: Even if your element doesn't have an existing class you have to add empty class attribute class="". Instead this will not work as expected. :( Better solution is to use preg_replace_callback. Then you can check if a match exists and create your p tags more accurately.