【发布时间】:2016-02-22 15:21:06
【问题描述】:
示例字符串(html内容):
some content
<h2>title 1</h2>
<p>more content</p>
<h2>title 2</h2>
rest of the content
我需要通过<h2></h2> 将其拆分为关联数组,但保留字符串的所有内容。
期望的输出:
array(){
'text1' => 'some content',
'title1' => 'title 1',
'text2' => '<p>more content</p>',
'title2' => 'title 2',
'text3' => 'rest of the content'
}
或
array(){
[0] => {
'text' => 'some content',
'title' => 'title 1'
},
[1] => {
'text' => '<p>more content</p>',
'title' => 'title 2'
},
[2] => {
'text' => 'rest of the content'
}
}
我尝试了什么
preg_split() 和 PREG_SPLIT_DELIM_CAPTURE 几乎可以完成这项工作,但它会输出索引数组。
我尝试使用正则表达式,但无法捕获 text3:
(.*?)(<h2.*?<\/h2>)
非常感谢任何帮助或想法。
【问题讨论】:
-
这些换行符是实际的新行吗?
-
是“一些内容”、“更多内容”……只有文本还是 html?
-
是的,内容是 HTML。
-
使用这个
(?s)(?:<h2>(.*?)</h2>|\s*(.+?)\s*(?=<h2>.*?</h2>|$))忘记那个重复的垃圾。如果 html 被垃圾,使用 DOM 解析 html 将失败。使用有效的东西。或者,您可以尝试找到可以通过格式错误的 html 的 DOM 解析器(但您不能)。 -
我去看看,谢谢。
标签: php arrays regex split preg-split