2017-09-27 140 views
0

我使用PHP简单的html dom解析器库,我只想用[WORD FIND HERE]替换所有'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

我明白了。那么使用解析是个好主意。我想你也可以使用正则表达式。 (* s/a矫枉过正/矫枉过正/) – lumio

回答

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; 
?>