2011-11-05 72 views
0

我是PHO DOM解析器的新成员。我有一个这样的字符串:PHP 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"; 

,我想改变的链接的所有文本(在本例中,马尔科链接)与自定义字符串,让说招呼

如何在PHP上执行此操作?目前,我只initilized的XDOM/XPATH解析器:

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

回答

2

你有一个良好的感觉对于此处的xpath,以下示例显示如何选择0123的所有文本节点子项(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

尝试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 
+0

不,谢谢,我想使用'DOMDocument'和'DOMXpath' – markzzz

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; 
+0

是的,但我想改变它的值,不要将它存储在数组中:) – markzzz

+0

用'$ link-> nodeValue = “你好”;',但它不起作用... – markzzz

+0

你应该能够从那里得到你想要的东西,但我已经编辑了我的答案,以你的喜好。对于那个很抱歉。 –

相关问题