多次 <br /><br><br/>\r\n 需要替换为 <br />

Multiple <br /><br><br/>\r\n occurences needs to be replaced with <br />

我需要将多次出现的 <br /><br><br/>\r\n\r\n 替换为 1 <br />,但只有在它一起出现的地方,这样我才能将段落拆分成一个数组,并 trim 去掉字符串末尾 br 标记的最后一个换行符...

字符串示例如下:

This is paragraph 1<br>

This is paragraph 2<br /><br>



This is paragraph 3
This is paragraph 4


This is paragraph 5<br/>
This is paragraph 6


This is paragraph 7<br />This is paragraph 8

This is paragraph 9<br>

我尝试过的:

$description = !empty($results['Description']) ? strip_tags(rtrim(str_replace(array("\n", "\r", "\r\n", "<br>", "<br/>", "<br />"), array("<br />"), $results['Description']), '<br />'), '<br><a>') : '';

$paragraphs = array_filter(explode("<br />", $description));

但这trim排除了所有的换行符。我需要在字符串中保留换行符,但只想做 1 个换行符并删除所有其他换行符。如何做到这一点?

注意:我使用 strip_tags 因为我只想在 $description 字符串中使用 <br><a> 标签。

您可能想先尝试使用行尾 (PHP_EOL) 进行分解,去除除 <a> 之外的所有内容,然后是 array_filter()implode()trim():

$str    =   'This is paragraph 1<br>

This is paragraph 2<br /><br>



This is paragraph 3
This is paragraph 4


This is paragraph 5<br/>
This is paragraph 6


This is paragraph 7<br />';

$str    =   trim(implode('<br />'.PHP_EOL,array_filter(explode(PHP_EOL,strip_tags($str,'<a>')))));

echo $str;

给你:

This is paragraph 1<br />
This is paragraph 2<br />
This is paragraph 3<br />
This is paragraph 4<br />
This is paragraph 5<br />
This is paragraph 6<br />
This is paragraph 7

你的第二种情况:

$str    =   'This is paragraph 1<br>

This is paragraph 2<br /><br>



This is paragraph 3
This is paragraph 4


This is paragraph 5<br/>This is paragraph 5
This is paragraph 6


This is paragraph 7<br />';

# Explode on line breaks and remove empty lines
$exp    =   array_filter(explode(PHP_EOL,$str));
# Loop array and filter the lines
$new    =   array_map(function($v) {
                return strip_tags(trim($v,'<br>,<br />,<br/>'),'<a><br>');
            },$exp);
# Implode the array back
echo implode('<br />'.PHP_EOL,$new);

给你:

This is paragraph 1<br />
This is paragraph 2<br />
This is paragraph 3<br />
This is paragraph 4<br />
This is paragraph 5<br/>This is paragraph 5<br />
This is paragraph 6<br />
This is paragraph 7