Hi folks
Current image looks like
<img src="images/example.jpg" />
Now if img src
do not have the alt=""
, the code itself will replace the image like
<img src="images/example.jpg" alt="" />
How can be done with php?
Hi folks
Current image looks like
<img src="images/example.jpg" />
Now if img src
do not have the alt=""
, the code itself will replace the image like
<img src="images/example.jpg" alt="" />
How can be done with php?
The quickest solution, assuming images always follow that format, is this:
$search = '/<img src="([^"]+)" \/>/';
$replace = '<img src="$1" alt="" />';
$code = preg_replace( $search, $replace, $code );
However, I would question your motives. Adding a blank alt tag is pretty pointless.
if it is valid XML, you can use about any decent XML parser (SimpleXML for example), unmarshall the source, traverse the tree looking for image tags, try lookup the attribute and set it if it does not exist, and the remarshall the xml ...
should be a 10-liner or so ...
good luck ... :)
Here's an example of doing this with SimpleXML.
<?php
$html = '<html>
<body>
<img src="foo.jpg" />
</body>
</html>';
$xml = new SimpleXMLElement($html);
foreach ($xml->xpath('//img') as $img) {
if (!array_key_exists('alt', $img->attributes())) {
$img->addAttribute('alt', '');
}
}
echo $xml->asXML();
The output will be:
<?xml version="1.0"?>
<html>
<body>
<img src="foo.jpg" alt=""/>
</body>
</html>