douguanci9158 2016-04-29 08:11
浏览 160
已采纳

正则表达式:如果内部没有数据,则将<div>标签的内容替换为<br>标签

Code:

    <div>
      <font face="Arial, Verdana">
         <span style="font-size: 13.3333px;">
           <u>
             Hello World
           </u>
       </span>
    </font>
 </div>
    <div>
      <font face="Arial, Verdana">
         <span style="font-size: 13.3333px;">
           <u>
            Hello World2
           </u>
            <br>
       </span>
    </font>
 </div>
 <div>
    <br>
 </div>
 <div>
      <font face="Arial, Verdana">
        <span style="font-size: 13.3333px;">
           <u>
               <br>
            </u>
        </span>
      </font>
 </div>

Output:- I wish to get exactly the same output as given below

    <div>
      <font face="Arial, Verdana">
         <span style="font-size: 13.3333px;">
            <u>
             Hello World
            </u>
          </span>
       </font>
     </div>
    <div>
      <font face="Arial, Verdana">
         <span style="font-size: 13.3333px;">
           <u>
            Hello World2
           </u>
            <br>
       </span>
    </font>
 </div>
 <br>
 <br>

Here is what I have tried:

$html = preg_replace("/<div.*?>.*?<br.*?>.*?<\/div>/", "", $html);

but it is not working fine.

Please take a look on the code and suggest me how I can replace "div" tag from its starting to corresponding closing tag with "br" tag only when there is no text is present under "div" tag. As shown above in second "div" tag.

展开全部

  • 写回答

2条回答 默认 最新

  • duanan5940 2016-04-29 08:41
    关注

    I would highly suggest using DOM Manipulation to accomplish this. You can use regular expressions and you can make other solutions work. However, DOM Manipulation was created for this exact reason.

    There are many examples of DOM Parsers in PHP. Some are slower than others. Check out this SO post for a great listing of potential candidates for DOM Parsers.

    You could always use Regular Expressions - but here's the condition under which I would personally use a Regular Expression: If you never plan to add any other functionality to this. If you do plan to add more, change it up, make your script more versatile, etc., then I'd say don't use a RegEx. The reason is you will either end up with a huge, completely daunting expression, or you'll end up with many small "one-off" expressions. It will take you less time to reference a function inside a DOM Parser than it will to figure out the proper Regular Expression.

    EDIT:

    I've removed my code snippet - Splash58's answer is a more elegant solution. His example uses native PHP which 9.9 times out of 10 is better (quicker, more efficient, more community support, etc).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部