简体   繁体   English

Dom在标题和段落中拆分文本

[英]Dom split text in headers and paragraphs

I have a Html string like this: 我有这样的HTML字符串:

<h2>Header 1</h2>
  <p>Example line 1</p>
  <p>Example line 2</p>
  <p>Example line 3</p>
<h2>Header 2</h2>
  <p>Example line 1</p>
  <p>Example line 2</p>
...

I eventually want to convert this to Twitter Bootstrap tabs Html. 我最终希望将其转换为Twitter Bootstrap选项卡Html。 To be able to do that I prefer to have the string in one (or two) array(s): 为了做到这一点,我更喜欢将字符串放在一个(或两个)数组中:

'Header 1' => '<p>Example line 1</p><p>Example line 2</p><p>Example line 3</p>'
'Header 2' => '<p>Example line 1</p><p>Example line 2</p>'

What I have now: 我现在所拥有的:

$source = new \Htmldom();
$source->load($string);

foreach ($source->find('h2') as $item)
  {
    $tabs[] = $item->innertext;
    $panels[] = $item->next_sibling()->innertext;
  }

This gives me an array with the headers and an array with the first sibling of these headers (paragraphs in this example): 这给了我一个带有标题的数组和一个带有这些标题的第一个同级的数组(此示例中的段落):

array (size=2)
  0 => string 'Header 1' (length=10)
  1 => string 'Header 2' (length=9)

array (size=2)
  0 => string '<p>Example line 1</p>' (length=312)
  1 => string '<p>Example line 1</p>' (length=112)

Of course I want to have all the paragraphs, not just the first ones. 当然,我想拥有所有段落,而不仅仅是第一段。 It seems to me that this is not possible with this approach. 在我看来,用这种方法是不可能的。 Am I wrong? 我错了吗? How can I achieve this? 我该如何实现?

try to loop over elements and stop loop on h2. 尝试遍历元素并停止h2上的循环。

EXAMPLE: 例:

foreach ($source->find('h2') as $item)
  {
    $tabs[] = $item->innertext;
    $next_sibling=true;
    $item_next=$item;    
    while($next_sibling){
        $item_next=$item_next->next_sibling();
        $panels[$item->innertext][] = $item_next->innertext;
        if($item_next->next_sibling() == null || $item_next->next_sibling()->tag == 'h2')
            $next_sibling=false;    

    }        
  }  var_dump($tabs); var_dump($panels);

o/p: O / P:

array (size=2)
  0 => string 'Header 1' (length=8)
  1 => string 'Header 2' (length=8)
array (size=2)
  'Header 1' => 
    array (size=3)
      0 => string 'Example line 1' (length=14)
      1 => string 'Example line 2' (length=14)
      2 => string 'Example line 3' (length=14)
  'Header 2' => 
    array (size=2)
      0 => string 'Example line 1' (length=14)
      1 => string 'Example line 2' (length=14)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM