我想从一个包含所有h2标题的html字符串中自动生成一个目录,因此需要将它们放入一个数组中。
我有一个$text字符串,里面有格式化的html:
<h2>heading 1</h2>
<p>something</p>
<h2>heading 2</h2>
<p>something</p>
<h2>heading 3</h2>
<p>something</p>如何将h2中的所有标题提取到一个数组中?
我发现我需要正则表达式,也许是preg_match_all。
我试过了,但不起作用:
preg_match_all("<h2>(.*?)</h2>", $text, $found);
print_r($found);感谢您对初学者的帮助!
发布于 2021-09-22 17:21:29
将您的Regex更改为
preg_match_all('#<h2.*?>(.*?)</h2>#i',$text, $found);解释
<h2.*?> - ignore the classes/attributes in the tag if any
(.*?) - capture everything
</h2> - match end tag
i - ignore case 然后遍历数组并打印值
foreach ($found[1] as $a)
echo $a." ";https://stackoverflow.com/questions/69288608
复制相似问题