替换HTML元素内容

时间:2012-01-29 18:58:41

标签: php html

我有以下HTML。

<div class="red">Div One</div>
<div class="green">Div Two</div>
<div class="blue">Div Three</div>

用绿色类替换div中文本的最佳方法是什么?

另外,我需要一种通过元素名称()或元素名称和类()来检索标记内容的方法。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您可以使用某种HTML解析器。我会使用DOMDocumentphpQuery

在边缘情况下,您可以使用正则表达式。但我不建议你这样做!

$html = preg_replace('~(<div class="green">)(.*)(</div>)~', '$1Replacement$2', $html);

如果您想使用绿色选项,请使用

$html = preg_replace('~(<div( class="green">|>))(.*)(</div>)~', '$1Replacement$4', $html);

答案 1 :(得分:2)

jQuery可以为你做到

$(".green").empty().html("your new content for div");

并检索内容

var content=$(".blue").html();  //retrieves content inside class blue
相关问题