1

我有一个如下的 HTML 字符串:

$string = "\n<h2>heading 2</h2>\n\nwhatever we are doing is good to have one thing\n<h3>heading 3</h3>\nnext paragraph goes there\n<h2>new heading 2</h2>\n\npara succeeded for new heading 2\n\n<h2>heading 3</h2>\nand the rest of data";

我想要标题文本(即在 <h2> 和 </h2> 标记内)和后续文本(直到找到另一个 <h2>)或字符串结尾

我试过类似的东西:

$pattern = "/<h2>((?:(?!(<\/h2>)).)*)<\/h2>(.*?)(<h2>)?/is";

但这并没有达到预期的效果。

我想得到如下:

Array
(
[0] => Array
    (
        [0] => <h2>heading 2</h2>
        [1] => <h2>new heading 2</h2>
        [2] => <h2>heading 3</h2>
    )

[1] => Array
    (
        [0] => heading 2
        [1] => new heading 2
        [2] => heading 3
    )

[2] => Array
    (
        [0] => whatever we are doing is good to have one thing\n&lt;h3&gt; heading 3&lt;h3&gt;/h3&lt;h3&gt;\nnext paragraph goes there
        [1] => para succeeded for new heading 2
        [2] => and the rest of data
    )
)
4

1 回答 1

2

像这样试试

preg_match_all('#<h2>(.*)</h2>([^<]*+)#isU', $string, $match);
echo '<pre>' . htmlspecialchars(print_r($match, 1)) . '</pre>';

或者你可能需要这样

preg_match_all('#<h2>(.*)</h2>((?:(?!<h2>).)*+)#isU', $string, $match);

优化版

$pattern = '#<h2>(.*)</h2>(.*)(?=(?:<h2>|$))#isU';
于 2013-02-25T10:29:00.543 回答