How to add alt tag and alt message in the image tag by a custom script

Add the below code in your PHP script file:

How to add alt tag and alt message in the image tag by custom scriptexpoundsofttechsolution How to add alt tag and alt message in the image tag by custom script

<?php
$content = '
 <img src="one.jpg" alt="" />
 <img src="two.jpg" alt="" />
 <img src="three.jpg" />
 <img src="four.jpg" alt="xxxxxxx" />

 ';

 function replace_alt($html_content, $alt_text='')
 {   $count = preg_match_all('/<img[^>]+>/i', $html_content, $images);
    if($count>0)
 {   $o = $html_content;
        $t = 'alt="'.$alt_text.'" ';
       foreach($images[0] as $img)
        {   $is_alt = preg_match_all('/ alt="([^"]*)"/i', $img, $alt);
            if($is_alt==0)
          {   $new_img = str_replace('<img ', '<img '.$t , $img);
                $o = str_replace($img, $new_img, $o);
           }
             elseif($is_alt==1)
           {   $text = trim($alt[1][0]);
                if(empty($text))
               {   $new_img = str_replace(trim($alt[0][0]), $t, $img);
                    $o = str_replace($img, $new_img, $o);
                }
           }
        }
    }
    return $o;
 }

 echo replace_alt($content, 'this is a alt msg');
?> 

This code adds the alt message in the blank alt tag and also added the alt tag where the alt tag is doesn’t have in an image.