【问题标题】:Find and replace string in HTML using PHP DOM Parser使用 PHP DOM Parser 查找和替换 HTML 中的字符串
【发布时间】:2015-11-12 22:22:46
【问题描述】:

如何使用原生 PHP DOM 解析器在 html 页面中查找和替换字符串?

要查找的示例字符串:"the <a href='site.com'>company</a> has been growing for the past 5 months";

例如,父级是一个完整的 HTML 页面,该字符串的直接前导可以是 <div><p> 例如..

该元素没有 id 或 class。是否仍然可以找到并操纵它?

没有任何东西可以识别字符串或其直接前身。只有确切的字符串,即 $search_string 包含的字符序列。

谢谢!

编辑:

$string_to_replace = "the <a href='site.com'>company</a> has been growing for the past 5 months";

$replacement_string = "<span class='someClass'>the <a href='site.com'>company</a> has been growing for the past 5 months";</span>

【问题讨论】:

  • 你想用什么替换哪个字符串?
  • 在上面的示例中,您不搜索 DOM 元素的内容,而是搜索文本字符串。如果要修改<a href ... </a>,可以使用PHP DOM,但不要搜索"the <a href='site.com'>company</a> has been growing for the past 5 months"。使用字符串搜索/替换或正则表达式搜索/替换
  • 请参阅编辑。感谢您的澄清。我一直在尝试使用 str_replace() 但收效甚微。此外,人们说您不应该使用正则表达式解析 html(某些替换需要)。你能看看我发布的这个问题吗:stackoverflow.com/questions/33671497/…

标签: php parsing simple-html-dom domparser findandmodify


【解决方案1】:

由于这似乎跨越了带有子节点的节点的一部分,我会使用这样的替换:

// Text in $html
$find  = "the <a href='site.com'>company</a> has been growing for the past 5 months";
$find_len = strlen( $find );
$start = strpos( $html, $find );
if ( $start !== false ) {
    $html = substr( $html, 0, $start )
        . '<span class="someClass">' . $find . '</span>'
        . substr( $html, $start + $find_len );
}

我没有时间正确测试它,但它可能会为您指明正确的方向。

PHP DOM 可以很好地更改元素 a 的 href 属性或其内容(company)。如果 $find 是 &lt;div&gt;-element 的全部内容,它也应该工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2013-02-18
    • 2015-09-22
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多