PHP获取和设置标签属性 [英] PHP Getting and Setting tag attributes

查看:71
本文介绍了PHP获取和设置标签属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用php和DomDocument ....基本上我有一些html保存在db。使用不同URL的锚标签....我想强制锚定标签hrefs不在allowedurl列表中被替换为#

im being played by php and DomDocument.... basically i have some html saved in db. With anchor tags with different urls.... i want to force anchor tag hrefs not within allowedurl list to be replaced with #

例如

$allowed_url_basenames = array('viewprofile.php','viewalbum.php');

来自db1的示例内容

<table cellspacing="0" cellpadding="0">
<tbody>
    <tr>
        <td valign="top">
            <a href="viewprofile.php?userid=780">Edrine Kasasa </a> has &nbsp;
        </td>
        <td valign="top"> 
        invited 10 friend(s) to veepiz using the <a href="invite.php">Invite Tool</a>
        </td>
    </tr>
</tbody>

我想要一个PHP函数将保留第一个锚标签href,并将第二个锚点更改为href ='#'。

i want a php function that will leave first anchor tag href intact and change the second to href='#'.

推荐答案

这应该是非常直接的。

首先,我们来抓住所有的锚标签。 $ doc 是您创建的文档以HTML作为源

First, let's grab all of the anchor tags. $doc is the document you've created with your HTML as the source.

$anchors = $doc->getElementsByTagName('a');

现在我们逐一查看,并检查 href 属性。让我们假装,当传递的字符串在黑名单上时,函数 contains_bad_url 返回 true 。你需要自己写。

Now we'll go through them one-by-one and inspect the href attribute. Let's pretend that the function contains_bad_url returns true when the passed string is on your blacklist. You'll need to write that yourself.

foreach($anchors as $anchor)
    if($anchor->hasAttribute('href') && contains_bad_url($anchor->getAttribute('href'))) {
        $anchor->setAttribute('href', '#');
    }
}

Tada。那应该是全部的。您应该能够将结果作为XML字符串返回,并执行任何你需要做的其他事情。

Tada. That should be all there is to it. You should be able to get the results back as an XML string and do whatever you need to do with the rest.

这篇关于PHP获取和设置标签属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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