doute7910 2013-05-08 12:47
浏览 120
已采纳

正则表达式根据自定义标签拆分一些html内容

I need to split my html based on a custom html tag.

This is how my html looks like:

<div>
    <div id="header">
        <h1>Document Title</h1>
    </div>

    <div id="content">
        <p>Lorem ipsum dolar sit</p>
        <magicheader type="2" class="someClass">Header</magicheader>
        <p>Lorem ipsum dolar sit</p>
        <span><magicheader type="3" class="someClass">Header</magicheader></span>
    </div>

    <div id="footer">

    </div>
</div>

This is what I need:

Array
(
    [0] => <div>
    <div id="header">
        <h1>Document Title</h1>
    </div>

    <div id="content">
        <p>Lorem ipsum dolar sit</p>
    [1] => <magicheader type="2" class="someClass">Header</magicheader>
    [2] => <p>Lorem ipsum dolar sit</p>
        <span>
    [3] => <magicheader type="3" class="someClass">Header</magicheader>
    [4] => </span>
    </div>

    <div id="footer">

    </div>
</div>
)

Can anybody help me with the pattern?

  • 写回答

1条回答 默认 最新

  • duanjunjie0196 2013-05-08 12:59
    关注

    You need to use preg_split with PREG_SPLIT_DELIM_CAPTURE:

    $text=<<<EOD
    <div>
        <div id="header">
            <h1>Document Title</h1>
        </div>
    
        <div id="content">
            <p>Lorem ipsum dolar sit</p>
            <magicheader type="2" class="someClass">Header</magicheader>
            <p>Lorem ipsum dolar sit</p>
            <span><magicheader type="3" class="someClass">Header</magicheader></span>
        </div>
    
        <div id="footer">
    
        </div>
    </div>
    EOD;
    
    $regexp = '%(<magicheader [^>]*>Header</magicheader>)%';
    $value = preg_split($regexp, $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    

    Then print_r($value) outputs:

    Array
    (
        [0] => <div>
        <div id="header">
            <h1>Document Title</h1>
        </div>
    
        <div id="content">
            <p>Lorem ipsum dolar sit</p>
    
        [1] => <magicheader type="2" class="someClass">Header</magicheader>
        [2] => 
            <p>Lorem ipsum dolar sit</p>
            <span>
        [3] => <magicheader type="3" class="someClass">Header</magicheader>
        [4] => </span>
        </div>
    
        <div id="footer">
    
        </div>
    </div>
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含