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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示