1

如何使用原生 PHP DOM Parser 在 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>

4

1 回答 1

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 可以很好地更改元素的 href 属性a或其内容(公司)。如果 $find 是<div>-element的全部内容,它也应该工作

于 2015-11-12T23:15:40.473 回答