我有一个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";
我想要标题文字(即&lt; h2&gt;和&lt; / h2&gt;标记内)和后续文字(直到它找到另一个&lt; h2&gt;)或字符串结尾
我尝试过类似的事情:
$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<h3> heading 3<h3>/h3<h3>\nnext paragraph goes there
[1] => para succeeded for new heading 2
[2] => and the rest of data
)
)
答案 0 :(得分: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';