如何使用PHP中的simpleDOMparser替换整个HTML标签与alt文本等效?

时间:2012-06-22 03:25:18

标签: php replace simple-html-dom html

以下是一个例子:

我有一个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中引用此特定链接以便我可以对其进行修改?

1 个答案:

答案 0 :(得分:0)

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

$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;
} 

不知道这是否是“正确”的方式,但它会返回所需的输出。