保留锚标签并删除其他超链接
Keeping anchor tags and removing other hyperlinks
页面有链接到其他页面的超链接以及跳转到页面内某个位置的锚标记。我想保留锚标签并删除所有其他超链接。
锚标签示例:
<a class="footnote" href="#fnx" id="fnx_ref">x</a>
跳转到
<a class="footnote" href="#fnx_ref">x</a>
其中 x
是 1,2,3,4 ... n
。
页面中的所有其他超链接(带或不带 class 属性)都需要删除。如何才能做到这一点?我应该使用 php 正则表达式 吗?
与其使用 RegEx
在 html 中找到合适的标签,不如使用 DOMDocument
& DOMXPath
更容易,如下所示。
最后一行只是将编辑后的 html 回显到文本区域中,但您可以很容易地将其保存到文件中。
/* XPath expression to find all anchors that do not contain "#" */
$query='//a[ not ( contains( @href, "#" ) ) ]';
/* Some url */
$url='
/* 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>";
}
页面有链接到其他页面的超链接以及跳转到页面内某个位置的锚标记。我想保留锚标签并删除所有其他超链接。
锚标签示例:
<a class="footnote" href="#fnx" id="fnx_ref">x</a>
跳转到
<a class="footnote" href="#fnx_ref">x</a>
其中 x
是 1,2,3,4 ... n
。
页面中的所有其他超链接(带或不带 class 属性)都需要删除。如何才能做到这一点?我应该使用 php 正则表达式 吗?
与其使用 RegEx
在 html 中找到合适的标签,不如使用 DOMDocument
& DOMXPath
更容易,如下所示。
最后一行只是将编辑后的 html 回显到文本区域中,但您可以很容易地将其保存到文件中。
/* XPath expression to find all anchors that do not contain "#" */
$query='//a[ not ( contains( @href, "#" ) ) ]';
/* Some url */
$url='
/* 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>";
}