php 用php修改html属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16127142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:33:24  来源:igfitidea点击:

Modify html attribute with php

phpdom

提问by Linda

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

我有一个 html 字符串,其中正好包含一个 a 元素。例子:

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

In php I have to test if relcontains externaland if yes, then modify hrefand save the string.

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

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 relexists and contains external.

我一直在寻找 DOM 节点和对象。但是对于只有一个 A 元素来说,它们似乎太多了,因为我必须迭代以获取 html 节点,而且我不确定如何测试rel 是否存在并包含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?

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

采纳答案by u?nb??s

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

有没有更简单的方法,或者我应该用DOM来做吗?

Do it with DOM.

用 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();

回答by Linda

I kept going to modify with DOM. This is what I get:

我一直在用 DOM 进行修改。这就是我得到的:

$html = new DOMDocument();
$html->loadHtml('<?xml encoding="utf-8" ?>' . $txt);
$nodes = $html->getElementsByTagName('a');
foreach ($nodes as $node) {
    foreach ($node->attributes as $att) {
        if ($att->name == 'rel') {
            if (strpos($att->value, 'external')) {
                $node->setAttribute('href','modified_url_goes_here');
            }
        }
    }
}
$txt = $html->saveHTML();

I did not want to load any other library for just this one string.

我不想只为这个字符串加载任何其他库。

回答by HamZa

The best way is to use a HTML parser/DOM, but here's a regex solution:

最好的方法是使用 HTML 解析器/DOM,但这里有一个正则表达式解决方案:

$html = '<a href="http://www.test.com" rel="nofollow external">test</a><br>
<p> Some text</p>
<a href="http://test.com">test2</a><br>
<a rel="external">test3</a> <-- This won\'t work since there is no href in it.
';

$new = preg_replace_callback('/<a.+?rel\s*=\s*"([^"]*)"[^>]*>/i', function($m){
    if(strpos($m[1], 'external') !== false){
        $m[0] = preg_replace('/href\s*=\s*(("[^"]*")|(\'[^\']*\'))/i', 'href="http://example.com"', $m[0]);
    }
    return $m[0];
}, $html);

echo $new;

Online demo.

在线演示

回答by anthonybell

You could use a regular expression like if it matches /\s+rel\s*=\s*".*external.*"/then do a regExp replace like /(<a.*href\s*=\s*")([^"]\)("[^>]*>)/\1[your new href here]\3/

您可以使用正则表达式, if it matches /\s+rel\s*=\s*".*external.*"/然后进行 regExp 替换,例如 /(<a.*href\s*=\s*")([^"]\)("[^>]*>)/\1[your new href here]\3/

Though using a library that can do this kind of stuff for you is much easier (like jquery for javascript)

尽管使用可以为您完成此类工作的库要容易得多(例如 jquery for javascript)