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

Waz*_*aJB 2 php regex wordpress wysiwyg preg-replace

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

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

$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);
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,这段代码非常混乱,如果我能将它压缩成一个正则表达式,那将会很棒,但我只是缺乏这样做的能力.

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

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

我不确定如何使用上述内容,客户倾向于从其他网站复制内容,将其直接粘贴到新的WYSIWYG中,并且我看到了从hr标签到标题标签的任何内容.

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

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

非常感谢任何帮助,谢谢你的时间.

ene*_*nen 6

$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);
Run Code Online (Sandbox Code Playgroud)

结果:

<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>
Run Code Online (Sandbox Code Playgroud)

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