如何在 PHP 中使用 simpleDOMparser 将整个 HTML 标签替换为它们的替代文本等效项


How do I replace entire HTML tags with their alt text equivalent , using simpleDOMparser in PHP?

下面是一个例子:

我有一个 DOM 对象,$content从这个div 创建的:

<div class="content">&quot;test&quot; <!-- m -->
    <a class="postlink" href="http://imaginethisisareallylongurl.com">http://imagin...longurl.com</a><!-- m -->
    <img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" /> &quot;test&quot;
    <img src="./images/smilies/icon_e_sad.gif" alt=":(" title="Sad" /> sl
    <img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" />
    <img src="./images/smilies/icon_e_sad.gif" alt=":(" title="Sad" /> ok
</div>

我想得到这个输出:

"test" http://imaginethisisareallylongurl.com :D :( sl :D :( ok

div 中的图片标记将替换为其 alt 属性,网址将替换为其完整的 href 属性。

我该怎么做?

编辑:

像这样:

    foreach($content->find('a[class=postlink]') as $postlink)
    {
        $postlink->outertext = $postlink->href;
    }

不起作用。如何在$contents->innertext中引用此特定链接以便对其进行修改?

我应该更仔细地阅读文档。您可以像这样自定义解析行为:

$html->set_callback('custom_parse'); 

其中$html是您的原始 DOMDocument。

function custom_parse($element)
{
    if (isset($element->class)){
        if($element->class=='postlink'){
            $element->outertext = $element->href;
        }
    } 
    if (isset($element->innertext)){   
        $element->innertext = str_replace('<!-- m -->', '', $element->innertext);
    }
    if (isset($element->outertext)){   
        if ($element->tag=='img' and isset($element->alt)){
            $element->outertext = $element->alt;
        }
    }
}

那么在我的内容对象上,我可以调用它:

function parse_content($content)
{
    $content = $content->innertext;
    $content = strip_tags($content);
    $content = html_entity_decode($content);
    return $content;
} 

不知道这是否是"正确"的方法,但它返回所需的输出。