How to remove redundant
tags from HTML code u

2020-03-24 05:24发布

I'm parsing some messy HTML code with PHP in which there are some redundant
tags and I would like to clean them up a bit. For instance:

<br>

<br /><br /> 


<br>

How would I replace something like that with this using preg_replace()?:

<br /><br />

Newlines, spaces, and the differences between <br>, <br/>, and <br /> would all have to be accounted for.

Edit: Basically I'd like to replace every instance of three or more successive breaks with just two.

5条回答
我命由我不由天
2楼-- · 2020-03-24 05:49

Here is something you can use. The first line finds whenever there is 2 or more <br> tags (with whitespace between and different types) and replace them with wellformated <br /><br />.

I also included the second line to clean up the rest of the <br> tags if you want that too.

function clean($txt)
{
    $txt=preg_replace("{(<br[\\s]*(>|\/>)\s*){2,}}i", "<br /><br />", $txt);
    $txt=preg_replace("{(<br[\\s]*(>|\/>)\s*)}i", "<br />", $txt);
    return $txt;
}
查看更多
爷、活的狠高调
3楼-- · 2020-03-24 05:52

Try with:

preg_replace('/<br\s*\/?>/', '', $inputString);
查看更多
▲ chillily
4楼-- · 2020-03-24 05:56

This should work, using minimum specifier:

preg_replace('/(<br[\s]?[\/]?>[\s]*){3,}/', '<br /><br />', $multibreaks);

Should match appalling <br><br /><br/><br> constructions too.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-03-24 05:57

this will replace all breaks ... even if they're in uppercase:

preg_replace('/<br[^>]*>/i', '', $string);
查看更多
Ridiculous、
6楼-- · 2020-03-24 05:59

Use str_replace, its much better for simple replacement, and you can also pass an array instead of a single search value.

$newcode = str_replace("<br>", "", $messycode);
查看更多
登录 后发表回答