Changing Alt Attribute of images

I tumbled an issue recently that the elements don’t have an alt attribute, so I added a code that will set all empty alt with a random value.

function set_empty_img_alt_attribute( $filtered_image, $context, $attachment_id ) {

	$string = $filtered_image;
	$dom = new DOMDocument();
	@$dom->loadHTML($string);	
	$image = $dom->getElementsByTagName('img')->item(0);
	if($image->hasAttribute('alt')) {		
		if( $image->getAttribute('alt') == "" ) {
			$image->setAttribute('alt', 'dummy alt attribute');
			return($dom->saveXML($image));
		}
	} 
	return $filtered_image;
}
add_filter( 'wp_content_img_tag', 'set_empty_img_alt_attribute', 10, 3 );