PHP DOM解析器:查找所有链接的文本并进行更改 [英] PHP DOM Parser : find text of all links and change it

查看:125
本文介绍了PHP DOM解析器:查找所有链接的文本并进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入PHO DOM Parser。我有一个这样的字符串:

  $ coded_string =你好,我的名字是< a href =link1> Marco< / a>我希望< strong>更改< / strong> all< a href =link2>链接< / a>与自定义文本; 

我想更改链接中的所有文本(在示例中, Marco 链接)与自定义字符串,让我们说 hello



我该怎么做在PHP上?目前我只启动了XDOM / XPATH解析器:

  $ dom_document = new DOMDocument(); 
$ dom_document-> loadHTML($ coded_string);
$ dom_xpath = new DOMXpath($ dom_document);


解决方案

你对这里的xpath有好的感觉,示例显示如何选择所有文本节点子项( DOMText < a> 元素的c $ c> 文档 ) / p>

  $ dom_document = new DOMDocument(); 
$ dom_document-> loadHTML($ coded_string);
$ dom_xpath = new DOMXpath($ dom_document);

$ texts = $ dom_xpath-> query('// a / child :: text()');
foreach($ texts as $ text)
{
$ text-> data ='hello';
}

让我知道这是否有帮助。


I'm new into PHO DOM Parser. I have a string like this :

$coded_string = "Hello, my name is <a href="link1">Marco</a> and I'd like to <strong>change</strong> all <a href="link2">links</a> with a custom text";

and I'd like to change all text in the links (in the example, Marco and links) with a custom string, let say hello.

How can I do it on PHP? At the moment I only initilized the XDOM/XPATH parser as :

$dom_document = new DOMDocument();      
$dom_document->loadHTML($coded_string);
$dom_xpath = new DOMXpath($dom_document);

解决方案

You have a good sense for xpath here, the following example shows how to select all textnode children (DOMTextDocs) of the <a> elements and change their text:

$dom_document = new DOMDocument();      
$dom_document->loadHTML($coded_string);
$dom_xpath = new DOMXpath($dom_document);

$texts = $dom_xpath->query('//a/child::text()');
foreach ($texts as $text)
{
    $text->data = 'hello';
}

Let me know if this is helpful.

这篇关于PHP DOM解析器:查找所有链接的文本并进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆