我是PHO DOM解析器新手。我有一个这样的字符串:
$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和链接)与自定义字符串,让说hello。
如何在PHP上实现?目前,我只将XDOM/XPATH解析器初始化为:
$dom_document = new DOMDocument();
$dom_document->loadHTML($coded_string);
$dom_xpath = new DOMXpath($dom_document);
这里您对xpath有了很好的了解,下面的示例展示了如何选择<a>
元素的所有textnode子元素(DOMText
Docs)并更改它们的文本:
$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';
}
如果有帮助请告诉我
试试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
<?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;