如何从PHP中的HTML文件中的所有<img/>标记中删除所有“alt”属性?

时间:2012-12-12 13:45:01

标签: php image alt

  

可能重复:
  Remove style attribute from HTML tags

当前图片看起来像

<img src="images/sample.jpg" alt="xyz"/>

现在我想删除HTML文件中所有标签中存在的所有这些alt标签,PHP代码本身应该替换所有alt属性外观。 输出应该是这样的 仅<img src="images/sample.jpg" /> 如何用PHP完成?

先谢谢

4 个答案:

答案 0 :(得分:1)

使用DOMDocument进行HTML解析/操作。下面的示例读取HTML文件,从所有alt标记中删除img属性,然后打印出HTML。

$dom = new DOMDocument();
$dom->loadHTMLFile('file.html');

foreach($dom->getElementsByTagName('img') as $image)
{
    $image->removeAttribute('alt');
}

echo $dom->saveHTML(); // print the modified HTML

答案 1 :(得分:1)

首先,您需要暂停要修改的文档源。目前尚不清楚是否要编辑服务器上的某些html文件,编辑请求生成的html输出或者...

在这个答案中,我将逐步介绍如何使用HTML。它可以是file_get_contents('filename.html');some magic with output buffering

由于you don't want to parse HTML with regular expressions,您需要使用解析器:

由于HTML需要alt属性才有效,如果要“删除”它,则必须将其设置为空字符串。

这应该有效:

$doc = DOMDocument::loadHTML($myhtml);
$images = $doc->getElementsByTagName('img'); 

foreach($images as $img) {
    $image->setAttribute('alt', '');
}

$myhtml = $doc->saveHTML();

答案 2 :(得分:0)

阅读您的文件。您可以使用file_get_contents()来读取文件

$fileContent = file_get_contents('filename.html');
$fileContent = preg_replace('/alt=\"(.*)\"/', '', $fileContent);
file_put_contents('filename.html', $fileContent);

确保您的文件可写

答案 3 :(得分:0)

对于有效的xHTML,它应该具有alt属性。

这样的事情会起作用:

$xml = new SimpleXMLElement($doc);   // $doc is the html document.
foreach ($xml->xpath('//img') as $img_tag) {
    if (isset($img_tag->attributes()->alt)) {
        unset($img_tag->attributes()->alt);
    }
}
$new_doc = $xml->asXML();