2015-07-21 48 views
0

XHTML:如何交叉引用锚标签?

<root> 
<a href="1#fn1" class="fn-ref" id="s9781473910270.i11"><sup>1</sup></a> 
<p>some text<a href="1#fnref1" id="s9781473910270.i237">↩</a></p> 
</root> 

从上面的样品,如果两个锚的href相同(如1#fn11#fnref1)然后必须交换它们ID's作为其href,并具有包裹锚标签(其具有fnref在它们的href中)与<span class="label-fn">然后需要为该定位标记设置class="ref-fn-ref"

预期输出:

<root> 
<a href="#s9781473910270.i237" class="fn-ref" id="s9781473910270.i11"><sup>1</sup> 
</a> 
<p>sometext<span class="label-fn"><a href="#s9781473910270.i11" class="ref-fn-ref" 
id="s9781473910270.i237">↩</a></span></p> 
</root> 

到目前为止我试过,

libxml_use_internal_errors(true); 
$dom = new DOMDocument; 
$dom->loadHTMLFile("sample.xhtml", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); 
$xp = new DOMXPath($dom); 
$xp->registerNamespace("php", "http://php.net/xpath"); 
$className="fn-ref"; 
$anchor1 = $xp->query("//[contains(@class, '$className')]"); 
//???? 

我之间stucked中,我不知道如何与另一个匹配锚标签的数组anchor1数组。

回答

0

想通了自己得到我的输出。

$dom = new DOMDocument; 
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); 
$xp = new DOMXPath($dom); 
$xp->registerNamespace("php", "http://php.net/xpath"); 
$a1 = $xp->query("//*[contains(@class, 'fn-ref')]"); 
$a2 = $xp->query("//*[contains(@href, '#fnref')]"); 

foreach($a1 as $a1v) { 
    $id1=$a1v->getAttribute('id'); 
    preg_match("/([\\d]+)#fn([\\d+])/s",$a1v->getAttribute('href'),$m1); 
    $href1=$m1[1]."#fnref".$m1[2]; 
    foreach($a2 as $a2v) { 
    if($a2v->getAttribute('href')===$href1){ 
     $id2=$a2v->getAttribute('id'); 
     $a2v->setAttribute('class','ref-fn-ref'); 
     $a2v->setAttribute('href',"#".$id1); 
     $a1v->setAttribute('href',"#".$id2); 
     break; 
    } 
} 
} 
$r=$dom->saveXML();