2017-09-27 5 views
0

私はPHPの単純なHTML DOMパーサライブラリを使用して、私は[ワードファインド]ですべての 'manteau'これは以下の私のコードで、タグにない単語では動作しません。それは強力なタグ内の単語 'manteau'でのみ動作します。どのようにすべてのノードのテキストを解析するのですか?PHPシンプルなHTML DOMパーサー - 単語を検索

注: str_replaceは解決策ではありません。 DOM PARSERをここで使用する必要があります。私は、アンカータグまたは画像タグで単語を選択したくありません。

<?php 

    require_once '../simple_html_dom.php'; 
    $html = new simple_html_dom(); 
    $html = str_get_html('Un manteau permet de tenir chaud. Ce n\'est pas 
    un porte-manteau. Venez découvrir le <a href="pages/manteau">nouveau 
    manteau</a> du porte-manteau. 
    <h1>Tout savoir sur le Manteau</h1> 
    <p> 
     Le <strong>manteau</strong> est un élèment important à ne pas négliger. 
     Pas comme le porte-manteau. 
    </p> 
    <img src="path-to-images-manteau" title="Le manteau est beau">'); 


    $nodes = $html->find('*'); 

    foreach($nodes as $node) { 
     if(strpos($node->innertext, 'manteau') !== false) { 
      if($node->tag != 'a') 
       $node->innertext = '[WORD FIND HERE]'; 
      } 
     } 
    } 

    echo $html->outertext; 

?> 
+2

解析が少しだけここに単語を置き換えるためのやり過ぎのように聞こえます。なぜ単に 'str_replace'を使用しないのですか? – lumio

+0

dom操作はここで使用する必要があります。私はアンカーや画像タグ –

+0

私はunderstantに単語を選択したくないです。それでは、解析を使うことをお勧めします。私はあなたもこのために正規表現を使うことができると思います。 (* s/a過剰/過度/) – lumio

答えて

0

代わりにstr_replace();を使用してください。 http://php.net/manual/en/function.str-replace.php

$html = str_replace('manteau', 'rubber chicken', $html); 
echo $html; 

ここを参照してください。 https://3v4l.org/GRfji

+0

あなたの答えをありがとうが、str_replaceは解決策ではありません。ここではDOM操作を使用する必要があります。私は、アンカーまたはイメージタグで単語を選択したくありません。 –

0

あなたが変更したくないタグを除外するオプションかもしれません。例えば

<?php 
require_once '../simple_html_dom.php'; 
$html = new simple_html_dom(); 
$html = str_get_html('Un manteau permet de tenir chaud. Ce n\'est pas 
un porte-manteau. Venez découvrir le <a href="pages/manteau">nouveau 
manteau</a> du porte-manteau. 
<h1>Tout savoir sur le Manteau</h1> 
<p> 
    Le <strong>manteau</strong> est un élèment important à ne pas négliger. 
    Pas comme le porte-manteau. 
</p> 
<img src="path-to-images-manteau" title="Le manteau est beau">'); 


$nodes = $html->find('*'); 

$tagsToExclude = [ 
    "a", 
    "img" 
]; 

foreach($nodes as $node) { 
    if (!in_array($node->tag, $tagsToExclude)) { 
     if(strpos($node->innertext, 'manteau') !== false) { 
      $node->innertext = str_replace("manteau", '[WORD FIND HERE]', $node->innertext); 
     } 
    } 
} 

echo $html->outertext; 
?> 
関連する問題