简体   繁体   English

PHP替换a中的文本<h1></h1>标签

[英]PHP replace text within a <h1> </h1> tag

I'm using AJAX to call a PHP file which will effectively edit particular bits of content within another HTML file.我正在使用 AJAX 调用 PHP 文件,该文件将有效地编辑另一个 HTML 文件中的特定内容位。 My problem is that I'm not sure of the best way of targeting these particular areas.我的问题是我不确定针对这些特定区域的最佳方法。

I figured some sort of unique identifier would need to attached to the tag that needs to be edited or in a comment perhaps, and then PHP simply searches for this before doing the replacing?我认为需要将某种唯一标识符附加到需要编辑的标签或注释中,然后 PHP 在替换之前简单地搜索它?

Use simplehtml for this.为此使用simplehtml

You can change all <h1> to foo like this:您可以像这样将所有<h1>更改为foo

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

The simplehtmldom framework allows you to search and modify the DOM of a HTML file or url. simplehtmldom 框架允许您搜索和修改 HTML 文件或 url 的 DOM。

http://simplehtmldom.sourceforge.net/ 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>';

Another nice library is querypath.另一个不错的库是 querypath。 It is very similar to jquery:它与 jquery 非常相似:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM