如何从未被 HTML 标记包围的字符串中删除文本


How to remove text from a string that is not surrounded by HTML tags?

所以基本上我有一个很大的刺痛(几段长)。

我需要从此字符串中删除未被任何 HTML 标记包围的所有文本。

例如,此字符串:

<h1>This is the title</h1>This is a bit of text with no HTML around it<p>This is within a paragraph tag</p>

应转换为:

<h1>This is the title</h1><p>This is within a paragraph tag</p>

我相信这最好用正则表达式来完成,尽管我对它的 synax 不是很熟悉。

非常感谢所有帮助。


这是我最终使用的:

<?php
$string = '<h1>This is the title</h1>This is a bit of text with no HTML around it<p>This is within a paragraph tag</p>';
$pattern = '/(<'/[^>]+>)[^<]*(<[^>]+>)/';
$replacement = '$1$2';
echo preg_replace($pattern, $replacement, $string);
?>

您可以使用此正则表达式(<'/[^>]+>)[^<]*(<[^>]+>)并替换为$1$2现场演示