只替换HTML标签之外的单词

时间:2017-06-02 10:38:47

标签: php regex dom preg-replace

我想替换HTML标签之外的单词。

所以,如果我有

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

我想用“Bye”替换“Hello”我希望得到这个结果:

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

好吧,我了解到我必须使用DOM解析器才能实现这一点。

所以我使用https://github.com/sunra/php-simple-html-dom-parser并将其包含在内。

现在我做了

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

获取dom的文本。

现在我可以遍历结果:

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

但遗憾的是,如果$item->title包含$ word,则HTML结构会被粉碎。

1 个答案:

答案 0 :(得分:0)

看起来有很多混乱。根据{{​​3}},$dom->find($tag)会返回所有代码的数组,但您正在寻找名为text的代码?

也许您应该尝试$test = $dom->find('a');

同样在您的代码中,不清楚变量$url$target$item来自何处:

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

这应该更好:

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