我希望将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);
正如你所看到的,这段代码非常混乱,如果我能将它压缩成一个正则表达式,那就太棒了,但我只是缺乏这样做的能力。
我认为这行代码是另一种选择。
$content = preg_replace('/<h(.*?)<\/h(.*?)>/si', '<p class="heading-$2"$1</p>', $content);
我不确定如何使用上述内容,客户倾向于从其他网站复制内容,将其直接粘贴到新的WYSIWYG中,我看到任何内容从hr标签到标题标签。
我需要的只是上面的单行,除了标签本身只能是2个特定字符(所以确保标签以H开头,然后是[1-6])。
我还要求它添加到p标签的类特定于使用数量,例如:heading-1,heading-2。
非常感谢任何帮助,谢谢你的时间。
答案 0 :(得分: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);
<强>结果:强>
<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 tags
。