用Dom Document PHP替换元素

时间:2012-12-05 09:47:50

标签: php dom domdocument

我使用PHP Dom Document加载一个html页面:

$doc = new DOMDocument();
@$doc->loadHTMLFile($url);

我在我的页面中搜索了所有"a"个元素,如果他们意识到我的情况,我需要替换<a href="blablablabla">My link is beautiful</a>My link is beautiful

这是我的循环:

$liens = $div->getElementsByTagName('a');
foreach($liens as $lien){
    if($lien->hasAttribute('href')){
        if (preg_match("/metz2/i", $lien->getAttribute('href'))) {
        //HERE I NEED TO REPLACE </a>           
        }
        $cpt++;
    }
}

你有什么想法吗?建议?谢谢:))

2 个答案:

答案 0 :(得分:0)

每当我需要使用PHP管理DOM时,我使用一个名为 PHP Simple HTLM DOM 解析器的框架。 (Link here

这很容易使用,这样的东西可能适合你:

// Create DOM from URL or file
$html = file_get_html('http://www.page.com/');

// Find all links 
foreach($html->find('a') as $element) {
    //Do your custom logic here if you need it, for example this extracts the inner contents of the a-tag, and puts it freely.
    $inner = $element->innertext;
    $element->outertext($inner);
}

//To echo modified html again:
echo $html;

答案 1 :(得分:-2)

也可以使用preg_replace完成:

$sText = '<a href="asdasdasd">Stackoverflow</a>';

$sText = preg_replace( '/<a.*>(.*)<\/a>/',  '$1', $sText );

echo $sText;
相关问题