0

I'm trying to put some HTML-informations in an array.

<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.

The result should be: (strip_tags for title and remove span for content)

[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...

user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 4
    I would suggest you tale a look at [PHP DOM](http://php.net/manual/en/book.dom.php) for doing this. but try `$content[$counter] .= $paragraphs[$i]` for a start. You should increment `$counter` on title change. – bansi Sep 20 '14 at 12:47

1 Answers1

1

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.

bansi
  • 55,591
  • 6
  • 41
  • 52