将字符串拆分为关联数组


Split string into associative array

示例字符串(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() with PREG_SPLIT_DELIM_CAPTURE 几乎可以完成这项工作,但它输出索引数组。
我尝试使用正则表达式,但它无法捕获文本3
(.*?)(<h2.*?<'/h2>)

任何帮助或想法都非常感谢。

你应该能够进行正则表达式拆分:

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

此处的示例文本看起来就像您的输入示例。 我们可以假设每 2 个拆分相当于一个<h2></h2>对,因此您可以根据它们的数组索引标记它们。

我让你做了一个非常快的功能,它只在你的内容上测试过,但也许它会对你有所帮助。

<?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);
?>

你可以在这里尝试一下:http://sandbox.onlinephpfunctions.com/code/e80b68d919c0292e7b52d2069128e21ba1614f4c