0

海,

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

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

...

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

4

3 回答 3

2

使用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();
于 2013-04-22T09:47:03.273 回答
0

If you need a jQuery solution try this

$(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.
    });
});

Play here

于 2013-04-22T09:54:08.137 回答
0

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

也许试试这段代码(我没有测试过):

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

希望这可以帮助 !再见 !

于 2013-04-22T09:51:44.433 回答