2016-09-28 14 views
0

ページには、他のページにリンクされたハイパーリンクとアンカータグがあり、ページ内の場所にジャンプします。私は、アンカータグを保持し、他のすべてのハイパーリンクを削除したいと思います。アンカータグを保持して他のハイパーリンクを削除する

アンカータグの例:

<a class="footnote" href="#fnx" id="fnx_ref">x</a> 

ジャンプx1,2,3,4 ... nある

<a class="footnote" href="#fnx_ref">x</a> 

へ。

ページ内の他のすべてのハイパーリンク(クラス属性ありまたはなし)を削除する必要があります。これはどうすればできますか? のPHP正規表現を使用する必要がありますか?

+0

正規表現 – RamRaider

+0

より 'DOMDocument'&' DOMXPath'を使用することが容易になるだろうが、ほとんどのソリューションを開こうとしました –

答えて

1

はむしろ、HTML内の適切なタグを見つけるために、RegExを使用するよりも、以下のようにDOMDocument & DOMXPathを使用するのはかなり簡単です。

最後の行は、最終的に編集されたhtmlをテキストエリアにエコーしますが、ファイルに簡単に保存できます。

/* XPath expression to find all anchors that do not contain "#" */ 
$query='//a[ not (contains(@href, "#")) ]'; 

/* Some url */ 
$url='http://stackoverflow.com/questions/39737604/keeping-anchor-tags-and-removing-other-hyperlinks-php-regex'; 

/* get the data */ 
$html=file_get_contents($url); 

/* construct DOMDocument & DOMXPath objects */ 
$dom=new DOMDocument; 
$dom->loadHTML($html); 
$xp=new DOMXPath($dom); 

/* Run the query */ 
$col=$xp->query($query); 

/* Process all found nodes */ 
if(!empty($col)){ 
    /* 
     As you are removing nodes from the DOM you should 
     iterate backwards through the collection. 
    */ 
    for ($i = $col->length; --$i >= 0;) { 
     $a = $col->item($i); 
     $a->parentNode->removeChild($a); 
    } 

    /* do something with processed html */ 
    echo "<textarea cols=150 rows=100>",$dom->saveHTML(),"</textarea>"; 
} 
関連する問題