1

特定の用語を探して 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」であるため発生します。

4

1 に答える 1

1

その式は属性値を返すべきではありません。これは、PHP XPath 実装のバグのようです。Xpath//では の略です/descendant-or-self::node()/。子孫には属性は含まれません。あったとしてもtext()、軸なしは の略でchild::text()、属性には子ノードがありません。http://www.w3.org/TR/xpath/#axes

したがって、回避策が必要です。使用している完全に展開された式は/descendant-or-self::node()/child::text()[contains(., "CLEA")]. それでは微調整してみましょう。の代わりに、要素のみに一致する をnode()試してください。*

/descendant-or-self::*/text()[contains(., "CLEA")]

または、軸text()でノード テストを直接使用してみてください。descendant-or-self

/descendant-or-self::text()[contains(., "CLEA")]
于 2013-07-29T15:44:44.610 に答える