2012-02-18 193 views
0

创建替换HTML元素内容的函数的最佳方式是什么?替换HTML标签内容

我已经研究过使用正则表达式来解决这个问题,但后来发现这种方法由于持久性问题并不适合。 PHP需要通过HTML继续循环才能找到所有/任何匹配项。

我需要创建一个函数,除了params。一个是元素的标签名称(),另一个是元素类名称(class =“someclass”)

如果设置了一个类,那么我需要用新内容替换该标签和类名的所有元素。

如果还没有设置类,那么应该只搜索标签名称。

<div>Replace Element Tag Contents</div> 
<div class="someclass">Replace Element Contents That uses specified class</div> 

任何帮助,非常感谢。 请让我知道,如果这没有意义!

+2

[How to parse and process HTML with PHP?](http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) – Gordon 2012-02-18 15:09:11

回答

1

我会使用jQuery,除非您明确需要使用PHP出于某种原因。

$('div.someclass').text('this will replace the text in all div's with the class someclass').removeClass('someclass').addClass('Your new class name');

我会读这也 http://api.jquery.com/text/

如果需要使用PHP有已经被建成一个真棒DOM解析器。 http://simplehtmldom.sourceforge.net/