Search code examples
phpimagepreg-match-all

Replace empty alt tag on <img> tag


I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags. For example: <img src="assets/img/test.png" alt="" title="I'am a title tag" width="100" height="100" />

What I wish to have: <img src="assets/img/test.png" alt="" title="I'am a title tag" alt="I'am a title tag" width="100" height="100" />

So: I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

preg_match_all('/<img[^>]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?


Solution

  • Using Regex is not a good approach you should use DOMDocument for parsing HTML. Here we are querying on those elements whose alt attribute is empty which is actually asked in question.

    Try this code snippet here

    <?php
    
    ini_set('display_errors', 1);
    
    $string=<<<HTML
    <img src="assets/img/test1.png" alt="" title="I'am a title tag" width="100" height="100" />
    <img src="assets/img/test2.png" alt="" title="I'am a title tag" width="100" height="100" />
    <img src="assets/img/test3.png" alt="" title="I'am a title tag" width="100" height="100" /> 
    HTML;
    
    $domDocument = new DOMDocument();
    $domDocument->loadHTML($string,LIBXML_HTML_NODEFDTD);
    
    $domXPath = new DOMXPath($domDocument);
    $results = $domXPath->query('//img[@alt=""]');
    foreach($results as $result)
    {
        $title=$result->getAttribute("title");
        $result->setAttribute("alt",$title);
        echo $domDocument->saveHTML($result);
        echo PHP_EOL;
    }