dpfw3607 2017-03-31 05: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-31 06: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.

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

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决