PHP简单html dom解析器-查找单词 [英] PHP simple html dom parser - find word

查看:63
本文介绍了PHP简单html dom解析器-查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use the PHP simple html dom parser library and I want to replace only all 'manteau' word by [WORD FIND HERE]. This is my code below which doesn't work with words which are not in tags. It only works with the word 'manteau' within the strong tag. How to parse all nodes texts?

注意: str_replace不是解决方案.此处需要使用DOM PARSER.我不想在锚点或图像标签中选择单词.

Note : str_replace is not a solution. DOM PARSER need to be used here. I don't want to select the word in anchor or image tags.

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

?>

推荐答案

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

Maybe it is an option to exclude the tags that you do not want to change.

例如:

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

这篇关于PHP简单html dom解析器-查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆