php - 在将html解析为dom树时,如何在php中按标签分割字符串?

标签 php arrays string split

这是字符串:

<div>This is a test.</div>
<div>This <b>another</b> a test.</div>
<div/>
<div>This is last a test.</div>

我想将以下字符串分隔为数组,如下所示:

{"This is a test.", "This <b>another</b> a test.", "", "This is last a test."}

有什么想法可以在 php 中这样做吗?谢谢。

最佳答案

我假设您的 HTML 故意格式错误

有很多选项,包括 xpath 和众多库。 Regex is not a good idea 。我找到DOMDocument快速且相对简单。

getElementsByTagName 然后迭代它们以获得innerHTML。

示例:

<?php
function get_inner_html( $node ) { 
    $innerHTML= ''; 
    $children = $node->childNodes; 
    foreach ($children as $child) { 
        $innerHTML .= $child->ownerDocument->saveXML( $child ); 
    } 

    return $innerHTML; 
}
$str = <<<'EOD'
<div>This is a test.</div>
<div>This <b>another</b> a test.</div>
<div/>
<div>This is last a test.</div>
EOD;

$doc = new DOMDocument();
$doc->loadHTML($str);
$ellies = $doc->getElementsByTagName('div');
foreach ($ellies as $one_el) {
    if ($ih = get_inner_html($one_el))
        $array[] = $ih;
}
?>
<pre>
<?php print_r($array); ?>
</pre>

// Output
// Note that there would be
// a 4th array elemnt w/o the `if ($ih = get_inner_html($one_el))` check:
Array
(
    [0] => This is a test.
    [1] => This <b>another</b> a test.
    [2] => This is last a test.
)

Try it out here


注意:

只要没有嵌套 DIVS,上面的代码就可以正常工作。如果确实有嵌套,则必须在循环检查innerHTML 时排除嵌套的子级。

例如,假设您有以下 HTML:

<div>One
    <div>Two</div>
    <div>Three</div>
<div/>
<div>Four
    <div>Five</div>
</div>

以下是如何处理上述情况并获取一个按顺序排列数字的数组:

处理嵌套

<?php
function get_inner_html_unnested( $node, $exclude ) { 
    $innerHTML= ''; 
    $children = $node->childNodes; 
    foreach ($children as $child) {     
        if (!property_exists($child, 'tagName') || ($child->tagName != $exclude)) 
            $innerHTML .= trim($child->ownerDocument->saveXML( $child ));
    } 

    return $innerHTML; 
}
$str = <<<'EOD'
<div>One
    <div>Two</div>
    <div>Three</div>
<div/>
<div>Four
    <div>Five</div>
</div>
EOD;

$doc = new DOMDocument();
$doc->loadHTML($str);
$ellies = $doc->getElementsByTagName('div');
foreach ($ellies as $one_el) {
    if ($ih = get_inner_html_unnested($one_el, 'div'))
        $array[] = $ih;
}
?>
<pre>
<?php print_r($array); ?>
</pre>

Try it out here

关于php - 在将html解析为dom树时,如何在php中按标签分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6854669/

相关文章:

javascript - 如何访问 PHP 标签内的 javascript 变量?

java - 如何将三个有序数组合并为一个有序数组?在 O(n) 中

c - 怎么可能读写数组

c - scanf 跳过函数

python - 'String' 模块对象没有属性 'join'

ruby - 数字到英文单词 ruby

php - 从用户到帖子和类别的多态多对多

php - 没有得到正确的经纬度和完整地址

javascript - Jquery 对话框删除行

objective-c - 在 Objective-C 中设置数组的内容