-3

我需要根据自定义 html 标签拆分我的 html。

这就是我的 html 的样子:

<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>

这就是我需要的:

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>
)

任何人都可以帮我设计模式吗?

4

1 回答 1

1

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>
)
于 2013-05-08T12:59:50.433 回答