【发布时间】: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