读取一个HTML标记的属性并将其写入另一个HTML标记的属性

时间:2012-12-19 12:22:46

标签: php html

我有一个带有“alt”属性的HTML <img>。我的<img>包含在<a>中。 <a>具有“标题”属性。例如:

<a title="" href ="page.html"><img src="image.jpg" alt="text"></a>

我需要读取<img>的“alt”属性的值,并将其写入<a>的“title”属性值。有没有办法在PHP中执行此操作?

5 个答案:

答案 0 :(得分:2)

你可以通过php

来做到这一点
$url="http://example.com";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
       echo $tag->getAttribute('alt');
}

答案 1 :(得分:1)

由NullPointer发起,

  $url="http://example.com";

  $html = file_get_contents($url);

  $doc = new DOMDocument();
  @$doc->loadHTML($html);

  $tags = $doc->getElementsByTagName('img');

  foreach ($tags as $tag) {
     $parent = $tag->parentNode;
     if($parent->nodeName == 'a') {
         $parent->setAttribute('tittle', $tag->getAttribute('alt'));
     }
  }

希望有所帮助

答案 2 :(得分:0)

您可以尝试使用JQUERY,

<script>
    var altValue = $('img').attr('alt');
    $('a').attr('title', altValue);
</script>

你需要在onClick上使用它,如果你有更多的img和标签,如下所示

<script>
    function changeTitle(this) {
        var altValue = $(this).find('img').attr('alt');
        $(this).find('a').attr('title', altValue);
    }
</script>

答案 3 :(得分:0)

PHP是一种服务器端语言。因此,一旦输出呈现,您就不能再进行更改了。 (除非您使用PHP下载内容然后输出更改的数据,但这似乎只有在您无法访问orignal源时才有用)如果您正在创建输出IN php,您可以使用:

$alt = 'text';
echo '<a title="'.$alt.'" href ="page.html"><img src="image.jpg" alt="'.$alt.'"></a>';

如果您已有输出,则可以使用jquery(http://jquery.com/

<script type='text/javascript'>
//perform after page is done
$(function() {

  //each image in an a tag
  $('a img').each(function() {
    var $el = $(this);
    var alt = $el.attr('alt');
    $el.parent('a').attr('title', alt);
  });
});
</script>

更新

如果纯PHP字符串修改,你也可以使用正则表达式来改变它,而不是dom操作:

$string = '<a title="" href ="page.html"><img src="image.jpg" alt="text"></a>';
$pattern = '/<a(.*?)title="(.*?)"(.*?)<img(.*?)alt="(.*?)"(.*?)<\/a>/i';
$replacement = '<a${1}title="$5"${3}<img${4}alt="${5}"${6}</a>';
echo preg_replace($pattern, $replacement, $string);

答案 4 :(得分:0)

虽然问题标记为,但我认为我会提供一种简单明了的JavaScript,即客户端做同样的事情:

function attributeToParent(tag, from, to, within) {
    if (!tag || !from || !to) {
        return false;
    }
    else {
        within = within && within.nodeType == 1 ? within : document;
        var all = within.getElementsByTagName(tag);
        for (var i = 0, len = all.length; i < len; i++) {
            if (all[i].getAttribute(from) && all[i].parentNode.tagName.toLowerCase() !== 'body') {
                all[i].parentNode.setAttribute(to, all[i].getAttribute(from));
            }
        }
    }
}

attributeToParent('img', 'alt', 'title');​

JS Fiddle demo

这可以在一定程度上整理,但我认为它相对清晰(虽然比我想要的更麻烦)。

参考文献: