繁体   English   中英

PHP简单HTML DOM解析器-查找单词

[英]PHP simple html dom parser - find word

我使用PHP简单的html dom解析器库,并且只想用[WORD FIND HERE]替换所有“ manteau”词。 这是我下面的代码,不适用于不在标签中的单词。 它仅在Strong标签中与单词“ manteau”一起使用。 如何解析所有节点文本?

注意: 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;

?>

使用str_replace(); 代替! http://php.net/manual/zh/function.str-replace.php

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

看到它在这里工作; https://3v4l.org/GRfji

也许可以选择排除您不想更改的标签。

例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM