用php修改html属性 [英] Modify html attribute with php

查看:264
本文介绍了用php修改html属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html字符串,其中只包含一个a元素。示例:

 < a href =http://www.test.com =nofollow external>试验< / A> 

在php中,我必须测试如果 rel 包含 external ,如果是,则修改 href 并保存字符串。



我已经查找了DOM节点和对象。但是对于只有一个A元素,它们似乎太多了,因为我必须迭代获取html节点,而且我不确定如果 rel 存在并且包含外部 >。

  $ html = new DOMDocument(); 
$ html-> loadHtml($ txt);
$ a = $ html-> getElementsByTagName('a');
$ attr = $ a-> item(0) - > attributes();
...

在这一点上,我要得到似乎是开销的NodeMapList 。有没有更简单的方法,或者我应该用DOM做?

解决方案


有没有更简单的方法是这样做还是应该用DOM?


使用DOM执行



这里有一个例子:

 <?php 
$ html ='< a href = http://example.com =nofollow external> test< / a>';
$ dom = new DOMDocument;
$ dom-> loadHTML($ html);
$ xpath = new DOMXPath($ dom);
$ nodes = $ xpath-> query(// a [contains(concat('',normalize-space(@rel),''),'external')]);
foreach($ nodes as $ node){
$ node-> setAttribute('href','http://example.org');
}
echo $ dom-> saveHTML();


I have a html string that contains exactly one a-element in it. Example:

   <a href="http://www.test.com" rel="nofollow external">test</a>

In php I have to test if rel contains external and if yes, then modify href and save the string.

I have looked for DOM nodes and objects. But they seem to be too much for only one A-element, as I have to iterate to get html nodes and I am not sure how to test if rel exists and contains external.

$html = new DOMDocument();
$html->loadHtml($txt);
$a = $html->getElementsByTagName('a');
$attr = $a->item(0)->attributes();
...

At this point I am going to get NodeMapList that seems to be overhead. Is there any simplier way for this or should I do it with DOM?

解决方案

Is there any simplier way for this or should I do it with DOM?

Do it with DOM.

Here's an example:

<?php
$html = '<a href="http://example.com" rel="nofollow external">test</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//a[contains(concat(' ', normalize-space(@rel), ' '), ' external ')]");
foreach($nodes as $node) {
    $node->setAttribute('href', 'http://example.org');
}
echo $dom->saveHTML();

这篇关于用php修改html属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆