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 (DOMText
Docs) 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.
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
<?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;