Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

php - Only replace words outside of HTML-tags

I would like to replace words outside of HTML-tags.

So if I got

<a href="test.html" title="Hello">Hello</a>

and I want to replace "Hello" with "Bye" I would like to get this result:

<a href="test.html" title="Hello">Bye</a>.

Well, I learned that I have to use a DOM-parser to achieve that.

So I used https://github.com/sunra/php-simple-html-dom-parser and included it.

Now I did

$test = $dom->find('text');

To get the text of the dom.

Now I can loop through the results:

foreach($test as $t) {
    if (strpos($t->innertext,$word)!==false) {
        $t->innertext = preg_replace(
                '/' . preg_quote( $word, "/" ) . '/i',
                "<a href='$url' target='$target' data-uk-tooltip title='$item->title'>$0</a>",
                $t->innertext,1
            );
    }
}

But unfortunately, if $item->title contains $word, the HTML-structure is smashed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like there was much confusion. According to the docs, $dom->find($tag) returns an array of all tags, but you are looking for a tag called text ?

Maybe you should try $test = $dom->find('a'); instead ?

Also in your code, it is not clear where the variables $url, $target and $item come from :

foreach($test as $t) {
    if (strpos($t->innertext,$word)!==false) {
        $t->innertext = preg_replace(
            '/' . preg_quote( $word, "/" ) . '/i',
            "<a href='$url' target='$target' data-uk-tooltip title='$item->title'>$0</a>",
            $t->innertext,1
        );
    }
}

This should work better:

foreach($test as $t) {
    if (strpos($t->innertext,$word)!==false) {
        $t->innertext = preg_replace(
            '/' . preg_quote( $word, "/" ) . '/i',
            "Replacement",
            $t->innertext,1
        );
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...