PHP Split html string into array

大兔子大兔子 提交于 2019-12-24 15:25:54

问题


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.


回答1:


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




回答2:


You could try something like:

preg_split("/<h4>.+</h4>/i", $html);



回答3:


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



来源:https://stackoverflow.com/questions/26893753/php-split-html-string-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!