文本处理并将其插入数据库

时间:2013-08-28 20:58:37

标签: php domdocument

我抓住了一个HTML代码并将其插入我的数据库。

看起来像这样,但我并不需要这个。我需要相同的HTML代码,但我希望其中的所有链接都有href =“#”,我不知道我该怎么做。

<div id="olpDivId"> <span class="olpCondLink" ><a class="buyAction olpBlueLink" href="/gp/offer-listing/B002YDZSQM/ref=dp_olp_new/192-2317768-5155903?ie=UTF8&condition=new">4&nbsp;new</a>&nbsp;from&nbsp;<span class="price">$164.99</span></span> <span class="olpCondLink" ><a class="buyAction olpBlueLink" href="/gp/offer-listing/B002YDZSQM/ref=dp_olp_used/192-2317768-5155903?ie=UTF8&condition=used">18&nbsp;used</a>&nbsp;from&nbsp;<span class="price">$80.00</span></span> <span class="olpCondLink" ><a class="buyAction olpBlueLink" href="/gp/offer-listing/B002YDZSQM/ref=dp_olp_refurbished/192-2317768-5155903?ie=UTF8&condition=refurbished">6&nbsp;refurbished</a>&nbsp;from&nbsp;<span class="price">$124.95</span></span> </div>

我是否清楚自己想要做什么?

最好的问候。

1 个答案:

答案 0 :(得分:1)

您可以使用 domDocument 来解析HTML并进行编辑:

<?php

    $html='<div id="olpDivId"> <span class="olpCondLink" ><a class="buyAction olpBlueLink" href="/gp/offer-listing/B002YDZSQM/ref=dp_olp_new/192-2317768-5155903?ie=UTF8&condition=new">4&nbsp;new</a>&nbsp;from&nbsp;<span class="price">$164.99</span></span> <span class="olpCondLink" ><a class="buyAction olpBlueLink" href="/gp/offer-listing/B002YDZSQM/ref=dp_olp_used/192-2317768-5155903?ie=UTF8&condition=used">18&nbsp;used</a>&nbsp;from&nbsp;<span class="price">$80.00</span></span> <span class="olpCondLink" ><a class="buyAction olpBlueLink" href="/gp/offer-listing/B002YDZSQM/ref=dp_olp_refurbished/192-2317768-5155903?ie=UTF8&condition=refurbished">6&nbsp;refurbished</a>&nbsp;from&nbsp;<span class="price">$124.95</span></span> </div>';
    $dom = new domDocument;
    $dom->loadHTML(  $html);
    $dom->preserveWhiteSpace = false;
    $links = $dom->getElementsByTagName("a");
    foreach($links as $link){
        $link->setAttribute('href','#');
    }
    echo $dom->saveHTML();

?>