dpfw3607 2017-03-30 21:44
浏览 42
已采纳

用一个单独的<br />替换<br />的多个连接实例

I am stripping HTML and replacing all <div> and <p> tags with <br /> tags. Problem is that I am left with random <br /> tags like

<br /><br /><br />
<br /><br />
<br /><br /><br /><br />

I am taking the body of an email and stripping tags like

$comment = strip_tags($comment,'<div><p>');
$comment = preg_replace("/<p[^>]*?>/", "", $comment);
$comment = str_replace("</p>", "<br />", $comment);
$comment = preg_replace("/<div[^>]*?>/", "", $comment);
$comment = str_replace("</div>", "<br />", $comment);

I want to be able to replace any instance of at least 2 <br /> tags next to each other with one single <br /> tag. At this point every <br /> will match exactly as I have shown, but...there is a possibility that they can vary like <br>, <br /> so just need to make sure that I can replace any type of br tag (when there are at least 2 of them) with one single one when they are sequentially repeated next to each other.

The "possibility" of a br tag looking like <br> is based on if it was already in the original HTML that I did not catch. I know I can do a str_replace("<br>", "<br />", $comment) but I was hoping to shorten my code and not add more lines.

Any idea how to do this? Im sure there is regex involved and preg_replace but not sure where to start.

  • 写回答

1条回答 默认 最新

  • doulu8341 2017-03-30 22:21
    关注

    When you run $comment = strip_tags($comment, '<div><p>'), there will be no <br> left as it is not an allowed tag. So the only <br /> would be from your four replacements below. You only need to care about the form "<br />" in the other words. But handling just <br /> vs. all other <br> form aren't much different in difficulty.


    Anyway, you could use:

    $comment = preg_replace('/(\s*<br[^>]*>){2,}/', '\1', $comment);
    
    • <br[^>]*> — match any kind of <br> tag
    • \s*<br[^>]*> — match zero or more whitespaces before the <br> tag
    • (\s*<br[^>]*>) — group this regex and capture into \1
    • (…){2,} — match two or more such groups.

    The replacement will keep the last <br> found.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部