【问题标题】:Only replace words outside of HTML-tags仅替换 HTML 标记之外的单词
【发布时间】:2017-11-03 17:54:55
【问题描述】:

我想替换 H​​TML 标记之外的单词。

如果我得到了

<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-&gt;title 包含 $word,则 HTML 结构会被破坏。

【问题讨论】:

  • 使用 DOMDocument
  • 你已经问过这个问题了一次stackoverflow.com/questions/44324332/…
  • 是的,有人告诉我使用 DOM-lib。我做到了。但这并不能解决我的问题。新案例;)
  • “嗯,我知道我必须使用 DOM 解析器来归档它。” ...我可以听到体育场周围的欢呼声,甚至还有墨西哥波!也许有希望毕竟!也许可以阻止小马! ... 更严肃一点:PHP 确实有 2 个非常好的内置 XML 解析器(与 HTML 一起使用):SimpleXML:php.net/manual/en/book.simplexml.php 和 DOMDocument:php.net/manual/en/class.domdocument.php - 为什么不使用其中一个?
  • @CD001:您无法使用 simplexml 解析 html 文档(大多数情况下不符合 xml),因此唯一的方法是 DOMDocument

标签: php regex dom preg-replace


【解决方案1】:

看起来有很多混乱。根据the docs$dom-&gt;find($tag)返回一个包含所有标签的数组,但是你正在寻找一个名为text的标签?

也许你应该改用$test = $dom-&gt;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
        );
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2016-10-02
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    相关资源
    最近更新 更多