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

时间:2011-11-05 10:30:13

标签: php string parsing dom

我是PHO DOM Parser的新手。我有一个这样的字符串:

$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";

我想用自定义字符串更改链接中的所有文字(在示例中, Marco links ),假设 hello < / em>的

我怎样才能在PHP上做到这一点?目前我只是将XDOM / XPATH解析器初始化为:

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

3 个答案:

答案 0 :(得分:2)

您对xpath有很好的理解,以下示例说明如何选择<a>元素的所有textnode子项(DOMTextDocs)并更改其文本:

$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';
}

如果这有用,请告诉我。

答案 1 :(得分:1)

尝试phpQuery(http://code.google.com/p/phpquery/):

<?php

    $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';

    require('phpQuery.php');

    $doc = phpQuery::newDocument($coded_string);
    $doc['a']->html('hello');
    print $doc;

?>

打印:

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

答案 2 :(得分:1)

<?php

$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";

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

$links = $dom_xpath->query('//a');
foreach ($links as $link)
{
    $anchorText[] = $link->nodeValue;
}

$newCodedString = str_replace($anchorText, 'hello', $coded_string);

echo $newCodedString;