【问题标题】:Split paragraphs into multidimensional array将段落拆分为多维数组
【发布时间】:2023-03-13 15:29:01
【问题描述】:

我正在尝试将一些 HTML 信息放入一个数组中。

<p>Title 1</p>
<p><span>Content 1</span></p>
<p><span>Content 2</span></p>

<p>Title 2</p>
<p><span>Content 1</span></p>
<p><span>Content 2</span></p>
<p><span>Content 3</span></p>

我想把这些放在一个包含“标题”和“内容”字段的数组中。我的问题是将那些具有跨度且属于同一标题的 p-tags 放在一起。

结果应该是:(标题为strip_tags,内容为remove span)

[0]['title'] => 'Title 1',
[0]['content'] => ' <p>Content 1</p><p>Content 2</p>',
[1]['title'] => 'Title 2',
[1]['content'] => ' <p>Content 1</p><p>Content 2</p><p>Content 3</p>',

我的尝试:

$paragraphs = explode('<p>', $html);
for ($i = 0 ; $i < count($paragraphs) ; $i++) {
    $paragraphs[$i] = '<p>' . $paragraphs[$i];
    if (strpos($paragraphs[$i], '<span') !== false) $content .= $paragraphs[$i];
    else $title = $paragraphs[$i];
}

但这会将所有内容合并到一个变量中。我需要上面的数组...

【问题讨论】:

  • 我建议你看看PHP DOM 这样做。但首先尝试$content[$counter] .= $paragraphs[$i]。您应该在标题更改时增加 $counter。

标签: php multidimensional-array explode


【解决方案1】:

您需要实现自己的计数器来检查标题更改。

$output = array();
$last_title=''; // store last title for reference
$counter=-1; //your counter
$paragraphs = explode('<p>', $html);
for ($i = 1,$c=count($paragraphs) ; $i < $c ; $i++) { //start from the second as there is always a blank row
    $paragraphs[$i] = '<p>' . $paragraphs[$i];
    if (strpos($paragraphs[$i], '<span') !== false) {
        $output[$counter]['content'] .= trim(strip_tags($paragraphs[$i],'<p>'));
    }
    else $title = $paragraphs[$i];
    if ($title != $last_title){
        $last_title = $title;
        $counter++;
        $output[$counter]['title'] = strip_tags($title);
        $output[$counter]['content'] = '';
    }
}
print_r ($output);

注意:我仍然建议使用 PHP DOM。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2017-12-19
    • 2013-05-04
    • 1970-01-01
    相关资源
    最近更新 更多