Skip to content

Instantly share code, notes, and snippets.

@pinscript
Created September 28, 2011 14:17
Show Gist options
  • Select an option

  • Save pinscript/1248055 to your computer and use it in GitHub Desktop.

Select an option

Save pinscript/1248055 to your computer and use it in GitHub Desktop.
Copy title attribute to missing/empty allt attributes
<?php
$html = '<html>
<head>
</head>
<body>
<img src="foo.jpg" title="heheh" alt="" />
<img src="foo.jpg" title="heheh" />
<img src="foo.jpg" title="heheh" alt="blaha" />
</body>
</html>';
function blah($html) {
$html = "<div>" . $html . "</div>";
$doc = new DOMDocument;
@$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$images = $xpath->query("//img[@title]");
foreach($images as $image) {
$alt = $image->getAttribute("alt");
if($alt == null || trim($alt) == "") {
$title = $image->getAttribute("title");
// No or empty alt tag
$image->setAttribute("alt", $title);
};
}
return trim(substr($doc->saveXML($doc->getElementsByTagName('div')->item(0)), 5, -6));
}
echo blah($html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment