将字符串拆分为关联数组[重复]

This question already has an answer here:

Example string (html content):

some content
<h2>title 1</h2>
<p>more content</p>
<h2>title 2</h2>
rest of the content

I need to split this into associative array by the <h2></h2>, yet keep all contents of the string.

Desired outputs:

array(){
  'text1' => 'some content',
  'title1' => 'title 1',
  'text2' => '<p>more content</p>',
  'title2' => 'title 2',
  'text3' => 'rest of the content'
}

or

array(){
  [0] => {
    'text' => 'some content',
    'title' => 'title 1'
  },
  [1] => {
    'text' => '<p>more content</p>',
    'title' => 'title 2'
  },
  [2] => {
    'text' => 'rest of the content'
  }
}

What I tried

preg_split() with PREG_SPLIT_DELIM_CAPTURE almost does the job, but it outputs indexed array.
I tried using regex, but it fails capturing text3:
(.*?)(<h2.*?<\/h2>)

Any help or idea is very appreciated.

</div>

you should be able to do a regex split:

preg_split ("/<\/?h2>/", sampletext)

where sampletext here looks just like your input example. we can assume that every 2 splits is equivalent to one <h2></h2> pair, so you can label them according to their array index.

I made you a function real quick, it has only been tested on your content, but maybe it will be helpful for you.

<?php
function splitTitlesAndContent($needle1,$needle2,$content){
    $spli = explode($needle1,$content);
    $arr = array();
    $titlenum = 1;
    $contentnum = 1;

    foreach($spli as $spl){
        $expl = explode($needle2,$spl);

        if(isset($expl[1])){
            $arr['title' . $titlenum] = trim($expl[0]);
            $titlenum++;

            $arr['content' . $contentnum] = trim($expl[1]);
            $contentnum++;
        }
        else{
            $arr['content' . $contentnum] = trim($expl[0]);
            $contentnum++;
        }
    }
    return $arr;
}

$content = 'some content
<h2>title 1</h2>
more content
<h2>title 2</h2>
rest of the content';

$splitted = splitTitlesAndContent('<h2>','</h2>',$content);
print_r($splitted);
?>

You can try it out here: http://sandbox.onlinephpfunctions.com/code/e80b68d919c0292e7b52d2069128e21ba1614f4c