我需要解析一大块 html 以查找特定术语,并将该术语的所有实例包装在 A 标记内(使用类“关键字”)。
为此,我使用 xpath 解析 html 位,它运行良好......
$nodes = $xpath->query('//text()[contains(., "CLEA")]');
除了在极少数情况下,术语在属性值内,在这种情况下会发生一些递归并且 html 中断:
Hello <a class="tag" title="this is <a class="tag" href="#">CLEA</a>">CLEA</a>, hello!
当我想要的是
Hello <a class="tag" title="this is CLEA">CLEA</a>, hello!
我正在努力纠正我的 xpath 查询以排除属于属性值的文本。
非常感谢您的帮助,谢谢。
以下是使用 Xpath 解析的 html 示例:
<?xml version="1.0" encoding="UTF-8"?>
<p>
Carte Blanche aux Artistes du <a class="tag" href="?tag=clea" rel="tag-definition" title="Click here to learn more about CLEA">CLEA</a>
14.01 - 19.01.2013
at:
Gare Numérique de Jeumont, France
Organised by:
DRAC, Nord-Pas de Calais
Education National Nord-Pas de Calais
In the context of :
CLEA, résidence-mission
Contrat Local d'Education Artistique
http://cleavaldesambre.wordpress.com/
With: Martin Mey, Stephane Querrec, Woudi Tat, Marie Morel, LAb[au]
LAb[au] featured projects: <a title="Click here to learn more about f5x5x1" href="?tag=f5x5x1" rel="tag-definition" class="tag">Framework f5x5x1</a>, kinetic light art installation
<a title="Click here to learn more about binary waves" href="?tag=binary+waves" rel="tag-definition" class="tag">binary waves</a>, cybernetic light art installation</p>
更新 2 xpath 像这样在 php 中使用
$dom = new DOMDocument('1.0', 'utf8');
$dom->formatOutput = true;
$dom->loadHTML(mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new DOMXPath($dom);
foreach ($tags as $t) {
$label = $t['label'];
$nodes = $xpath->query('//text()[contains(., "' . $label . '")]');
$urlVersion = htmlentities(urlencode($label));
foreach ($nodes as $node) {
$link = '<a class="tag" rel="tag-definition" title="Click to know more about ' . $label . '" href="?tag='.$urlVersion.'">'.$label.'</a>';
$replaced = str_replace($label, $link, $node->textContent);
$newNode = $dom->createDocumentFragment();
$newNode->appendChild(new DOMText($replaced));
$node->parentNode->replaceChild($newNode, $node);
}
}
$text= $dom->saveHTML();
发生错误是因为一个标签是“les amis de CLEA”,另一个标签是“CLEA”。