将图像替换为其alt标记


Replace an image with its alt-tag

Hoi,

我有一个字符串,里面充满了html内容。我现在需要做的是,用alt文本替换每个图像。

html可以看起来像这样:

<h1> some h1</h1>
<img src="images/image.jpg" alt="My Alt-text" width="540" height="304" />
<img src="images_2003/basket.jpg" alt="My other alt text" width="540" height="304" />
<h2>some h2</h2>
<img src="images/image2.jpg" alt="My next Alt-text" width="540" height="304" />
<img src="images/image45.jpg" alt="Yet other alt text" width="540" height="304" />
...

应该是什么:

<h1> some h1</h1>
My Alt-text
My other alt text
<h2>some h2</h2>
My next Alt-text
Yet other alt text
...

实现这一目标的最佳方式是什么?

使用DOM解析器,这非常简单:

$contents = <<<EOS
<h1> some h1</h1>
<img src="images/image.jpg" alt="My Alt-text" width="540" height="304" />
<img src="images_2003/basket.jpg" alt="My other alt text" width="540" height="304" />
<h2>some h2</h2>
<img src="images/image2.jpg" alt="My next Alt-text" width="540" height="304" />
<img src="images/image45.jpg" alt="Yet other alt text" width="540" height="304" />
EOS;
$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($contents);
libxml_clear_errors();
$xp = new DOMXPath($doc);
foreach ($xp->query('//img') as $node) {
        $text = $doc->createTextNode($node->getAttribute('alt') . "'n");
        $node->parentNode->replaceChild($text, $node);
}
echo $doc->saveHTML();

我认为您可以使用jquery来执行此操作。

也许试试这个代码(我没有测试它(:

$("img").each(function() {
    var alt_txt = $(this).attr('alt');
    $(this).replaceWith(alt_txt);
});

希望这能有所帮助!再见

如果您需要jQuery解决方案,请尝试此

$(document).ready(function() {
    var alt = ""
    $( "img" ).each(function( index ) {
      alt = $(this).attr("alt");
      $(this).replaceWith("<p>" + alt + "</p>");  // modify p with someother tag if needed.
    });
});

在此处播放