特定の用語を探して 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();
このエラーは、1 つのタグが「les amis de CLEA」で、別のタグが「CLEA」であるため発生します。