自动将html标记替换为“<;br>&”;


Automatically replace html-tags by "<br>"

我正在寻找一种用<br>替换html标记的方法。

函数str_replace不起作用,因为我不知道标签的属性。

输入字符串可能看起来像这样(例如):

$str = "line one<p class='one'>line two</p>line three<p/>line four</p>line five<br> line six<br /><p>line eight</p>";

应将其转换为:

$str = "line one<br>line two<br>line three<br>line four<br>line five<br>line six<br>line eight";

我想转换的标签是<p ....><br ... >,还有<div ....>

最好的方法是什么?

我不知道如何替换模式。

$str= "line one<p class='one'>line two</p>line three<p/>line four</p>line five<br> line six<br /><p>line eight</p>";
$str= preg_replace("/<p[^>]*?>/", "<br />", $str);
$str= str_replace("</p>", "<br />", $str);
echo $str= str_replace("<br /><br />", "<br />", $str);

一个快速而肮脏的正则表达式将是

$str = preg_replace('#<.*?>#', '<br />', $str);

这将用break标记替换所有标记,并且不会删除重复的标记。如果您想这样做,您可以更进一步,用一个实例替换多个实例。下面还添加了一个限定符,即只应替换p br和div标记。

$str = preg_replace('#</{0,1}[p|br|div].*?>#', '<br />', $str);
$str = preg_replace('#(<br />)+#', '<br />', $str);`

更好的解决方案是像其他人所说的那样解析DOM,但如果你想要快速简单的东西,那就是它

您应该编写这个

$str= "line one<p class='one'>line two</p>line three<p/>line four</p>line five<br> line six<br /><p>line eight</p>";
$str = preg_replace('#</{0,1}[p|br|div].*?>#', '<br />', $str);
$str = preg_replace('#(<br />)+#', '<br />', $str);`
$str= str_replace("</p>", "<br />", $str);
echo $str= str_replace("<br /><br />", "<br />", $str);