需要用<br/>替换多个发生的事故

时间:2016-09-14 04:20:51

标签: php str-replace paragraphs

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

字符串的示例如下:

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>

但这会减少所有换行符。我需要在字符串中保持换行符,但只想做1个换行符并删除所有其他换行符。怎么做?

注意:我使用的是strip_tags,因为我只想在$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)); 字符串中添加<br><a>个标记。

1 个答案:

答案 0 :(得分:2)

您可能希望首先尝试使用行尾(PHP_EOL)进行爆炸,除去<a>,然后array_filter()implode()和{{1 }}:

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);