将所有HTML img标记替换为ALT中的文本

时间:2012-08-29 06:54:11

标签: php preg-replace image alt

例如:

INPUT:

<img "img1.gif" alt="Donkey"><BR>
<img "img2.gif" alt="Horse"><BR>
<img "img3.gif" alt="Orangutan"><BR>

输出

Donkey
Horse
Orangutan

环顾四周,但没有雪茄。有任何想法吗?日Thnx!

3 个答案:

答案 0 :(得分:3)

今天感觉很慷慨,这里是da c0dez:

$html =<<<EOS
<img "img1.gif" alt="Donkey"><BR>
<img "img2.gif" alt="Horse"><BR>
<img "img3.gif" alt="Orangutan"><BR>
EOS;

$d = new DOMDocument;
$d->loadHTML($html);
foreach ($d->getElementsByTagName('img') as $img) {
    echo $img->getAttribute('alt'), "\n";
}

答案 1 :(得分:3)

使用preg_replace()

快速解决方案
$text = '<img img1.gif" alt="Donkey"><BR>
<img img2.gif" alt="Horse"><BR>
<img img3.gif" alt="Orangutan"><BR>';

$replace = preg_replace('/<img(.*)alt="(.*)"\>/', "$2", $text);
echo $replace;

答案 2 :(得分:0)

你无法环顾四周 - 看看这个非常相似的问题:

How to extract img src, title and alt from html using php?