[英]Split paragraphs into multidimensional array
I'm trying to put some HTML-informations in an array. 我正在尝试将一些HTML信息放入数组中。
<p>Title 1</p>
<p><span>Content 1</span></p>
<p><span>Content 2</span></p>
<p>Title 2</p>
<p><span>Content 1</span></p>
<p><span>Content 2</span></p>
<p><span>Content 3</span></p>
I want to put these in an array with the fields "title" and "content". 我想将它们放在带有“标题”和“内容”字段的数组中。 My problem is to put those p-tags together which has a span and belongs to the same title. 我的问题是将那些具有跨度且属于同一标题的p标签放在一起。
The result should be: (strip_tags for title and remove span for content) 结果应为:(strip_tags表示标题,而span表示内容)
[0]['title'] => 'Title 1',
[0]['content'] => ' <p>Content 1</p><p>Content 2</p>',
[1]['title'] => 'Title 2',
[1]['content'] => ' <p>Content 1</p><p>Content 2</p><p>Content 3</p>',
My attempt: 我的尝试:
$paragraphs = explode('<p>', $html);
for ($i = 0 ; $i < count($paragraphs) ; $i++) {
$paragraphs[$i] = '<p>' . $paragraphs[$i];
if (strpos($paragraphs[$i], '<span') !== false) $content .= $paragraphs[$i];
else $title = $paragraphs[$i];
}
But this will merge ALL content to one variable. 但这会将所有内容合并到一个变量中。 I need the above array... 我需要上面的数组...
You need to implement your own counter for checking title change. 您需要实现自己的计数器来检查标题更改。
$output = array();
$last_title=''; // store last title for reference
$counter=-1; //your counter
$paragraphs = explode('<p>', $html);
for ($i = 1,$c=count($paragraphs) ; $i < $c ; $i++) { //start from the second as there is always a blank row
$paragraphs[$i] = '<p>' . $paragraphs[$i];
if (strpos($paragraphs[$i], '<span') !== false) {
$output[$counter]['content'] .= trim(strip_tags($paragraphs[$i],'<p>'));
}
else $title = $paragraphs[$i];
if ($title != $last_title){
$last_title = $title;
$counter++;
$output[$counter]['title'] = strip_tags($title);
$output[$counter]['content'] = '';
}
}
print_r ($output);
Note: I still suggest PHP DOM. 注意:我仍然建议使用PHP DOM。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.