doufuxing8562 2011-11-05 10:30
浏览 9
已采纳

PHP DOM Parser:查找所有链接的文本并进行更改

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);
  • 写回答

3条回答 默认 最新

  • doutangliang7769 2011-11-05 11:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端