PHP替换<h1> </h1>标记内的文本

时间:2012-02-07 14:55:42

标签: php str-replace

我正在使用AJAX调用PHP文件,该文件将有效地编辑另一个HTML文件中的特定内容。我的问题是,我不确定针对这些特定领域的最佳方式。

我认为某些唯一标识符需要附加到需要编辑的标记或者注释中,然后PHP才会在替换之前搜索这个?

2 个答案:

答案 0 :(得分:2)

请使用simplehtml

您可以将所有<h1>更改为foo,如下所示:

$html = file_get_html('http://www.google.com/');
foreach($html->find('h1') as $element) 
{
  $element->innertext = 'foo';
}
echo $html;

答案 1 :(得分:1)

simplehtmldom框架允许您搜索和修改HTML文件或URL的DOM。

http://simplehtmldom.sourceforge.net/

// Create DOM from URL or file $html =
file_get_html('http://www.google.com/');

// Find all images foreach($html->find('img') as $element)
        echo $element->src . '<br>';

// Find all links foreach($html->find('a') as $element)
       echo $element->href . '<br>';

另一个不错的库是querypath。它与jquery非常相似:

 qp($html_code)->find('body')->text('Hello World')->writeHTML();

https://fedorahosted.org/querypath/wiki/QueryPathTutorial