简体   繁体   中英

PHP simple html dom parser - find word

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?

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;

?>

Use str_replace(); instead! http://php.net/manual/en/function.str-replace.php

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

See it working here; https://3v4l.org/GRfji

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

For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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