Created
September 28, 2011 14:17
-
-
Save pinscript/1248055 to your computer and use it in GitHub Desktop.
Copy title attribute to missing/empty allt attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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