PHP DOM Parser : find text of all links and change

2019-08-27 20:31发布

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条回答
家丑人穷心不美
2楼-- · 2019-08-27 21:06

Try 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;

?>

Prints:

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
查看更多
别忘想泡老子
3楼-- · 2019-08-27 21:20
<?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;
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-08-27 21:24

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.

查看更多
登录 后发表回答