替换所有没有';t以html标记开始和结束,该标记本身被包裹在<;p>;PHP中的元素


Replace all lines that don't start and end with a html tag with itself wrapped in a <p> elements in PHP?

我有一些来自TinyMCE编辑器的内容,由于某些原因,该编辑器在某些内容周围没有html标记。

我正在将导出和导入到一个新系统中,并希望通过将所有不以html标记开始和结束的行包装在"p"标记中来清理这一问题。

例如:

<h1>Heading 1</h1>
<p>This is the content of my first paragraph</p>
<h1>Heading 2</h1>
This is the content of my second paragraph
<h1>Heading 3</h1>
<p>This is the content of my third paragraph</p>

我希望它看起来像这样:

<h1>Heading 1</h1>
<p>This is the content of my first paragraph</p>
<h1>Heading 2</h1>
<p>This is the content of my second paragraph</p>
<h1>Heading 3</h1>
<p>This is the content of my third paragraph</p>

如果可能的话,我正在寻找一个使用RegEx的小型解决方案,并且已经尝试了很多方法。

有人有什么想法吗?

使用否定的前瞻性断言。断言在下面(向前看)或前面(向后看)的数据中检查其条件的存在(正)或不存在(负),但不使用任何字符。

类似于:

<?php
$cc = <<<'EOT'
<h1>Heading 1</h1>
<p>This is the content of my first paragraph</p>
<h1>Heading 2</h1>
    This is the content of my second paragraph
<h1>Heading 3</h1>
This is the content of my third paragraph
EOT;
$cc = trim($cc);
$dd = preg_replace('/^'s*(?![<])(.*?)('s*)$/m', '<p>$1</p>$2', $cc);
echo $dd;
?>

请参阅演示。

第二个括号中有's+,唯一的意义就是保持</p>在同一行但是,如果内容的最后一行没有被换行符终止,它就会失败

编辑:

  • 允许在行首处出现可能的空白
  • 修改了表达式以允许最后一行没有尾随换行符

trim()恰好可以确保测试数据的末尾没有空白。我还修改了测试数据,以反映新需求的测试可能性。

正则表达式执行以下操作:

  • 线路起点/^
  • 's*跳过开头的任何空白
  • (?![<])否定前瞻断言:如果下一个字符是"<",则失败
  • (.*?)捕捉行中的任何内容,但不要贪婪
  • ('s*),使得末尾的所有空白(尤其是换行符)都可以通过
  • 线路末端$
  • 多行/m处理:换行后可以匹配^,换行前可以匹配$

然后,这一行被第一个和第二个括号的内容(不考虑断言的内容,它总是零长度,并且没有被捕获)加上HTML标记所取代。