PHP Split html string into array

2019-08-07 03:07发布

I hope I can get some help from you guys.

This is what I'm struggling with, I have a string of HTML that will look like this:

<h4>Some title here</h4>
<p>Lorem ipsum dolor</p>
(some other HTML here)

<h4>Some other title here</h4>
<p>Lorem ipsum dolor</p>
(some other HTML here)

I need to split all the <h4> from the rest of the content, but for example the content after the first <h4> and before the second <h4> needs to be related to the first <h4>, something like this:

Array {
       [0] => <h4>Some title here</h4>
       [1] => <p>Lorem ipsum dolor</p>
}

Array {
       [0] => <h4>Some other title here</h4>
       [1] => <p>Lorem ipsum dolor</p>
}

This is to build an accordion (quite difficult to explain why I'm doing this way, but it has to be this way), and the <h4> will be the accordion panel headings and when clicked it will expand and show the content associated with them.

I hope I made my problem clear, let me know of your thoughts and how should I do this the better way.

I was looking into DOMDocument, but I also tried with explode() but with no success.

I have this working with JavaScript but I need to achieve the same thing with PHP, but it's quite complicated to play with the DOM with PHP.

Thank you in advance.

3条回答
做个烂人
2楼-- · 2019-08-07 03:57

This should do what you want -- though I'm sure there are other (and possibly better) ways

$aHTML = explode("<h4>", $cHTML);
foreach ($aHTML AS $nPos => $cPanel) {
  if ($nPos > 0) {
    $aPanel = explode("</h4>", $cPanel);
    $cHeader = "<h4>" . $aPanel[0] . "</h4>";
    $cPanelContent = $aPanel[1];
  }
}

It doesn't put it in the array format you stipulated -- though you could do that yourself inside the loop. Otherwise your content could be output/constructed inside the loop.

Edit: Added the h4 and /h4 back in for completeness

查看更多
够拽才男人
3楼-- · 2019-08-07 04:01

I was able to do what I wanted following the example that Derek S gave me.

This was the result:

$html_string = 'HTML string';
$dom = new DOMDocument();
$dom->loadHTML($html_string);

foreach($dom->getElementsByTagName('h4') as $node) {
   $title = $dom->saveHTML($node);
   $content[$title] = array();

   while(($node = $node->nextSibling) && $node->nodeName !== 'h4') {
      $content[$title] = $dom->saveHTML($node);
   }
}

This will save the titles inside $title and the correspondent content inside $content[$title].

查看更多
闹够了就滚
4楼-- · 2019-08-07 04:07

You could try something like:

preg_split("/<h4>.+</h4>/i", $html);
查看更多
登录 后发表回答