简体   繁体   中英

How can I automatically add the image "alt" attribute using image filename if it is missing, using php?

I need to add an image alt tag to hundreds of images. Problem is this would take forever and anyway there seems to be an easier solution.

I have been able to achieve this somewhat using javascript, as follows:

<script type='text/javascript'>  
 //<![CDATA[  
 $(document).ready(function() {  
  $('img').each(function(){  
   var $img = $(this);  
   var filename = $img.attr('src')  
    if (typeof attr == typeof undefined || attr == false) {
        $img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
    }  
  });  
 });  
 //]]>  
</script>

What this does is exactly what I want, so for example if I have this image:

<img src="http://mywebsite.com/images/the-image1.jpg" />

then the javascript will add the alt automatically like this:

<img src="http://mywebsite.com/images/the-image1.jpg" alt="the-image1" />

Well, that is all fine and dandy, but now I want to do it with PHP instead, because the problem is that this is only adding the tags into the front end which means it isn't visible from page source (only inspect element), which means that the search engine won't see the alt tag, which means that the only way to do it is to put it right into the page using php.

So how can I do my above javascript solution using php?

Does the filename consistently provide a meaningful slug? If not, you are better off just having empty alt tags. Web crawlers are already getting the image filename, so adding the last bit is only going to help if it is actually descriptive of the image. (It's also not 100% true it won't be indexed via JS, some bots, notably Google, do parse JavaScript to some degree.)

If the filename is not descriptive, it's probably going to do more harm than good (for SEO and screen readers). I assume you either are or will give descriptive filenames if you plan to use this scheme moving forward.

I'm assuming the images aren't content-managed in some way that you could pull from a caption or description for alt (and/or longdesc) attribute?

If it's a one-off fix, again depending on the quality of the naming, it might be ok. A few hundred images might not take that long, and there is always [advert removed] :)

Alternative text serves several functions:

  • It is read by screen readers in place of images allowing the content and function of the image to be accessible to those with visual or certain cognitive disabilities.
  • It is displayed in place of the image in browsers if the image file is not loaded or when the user has chosen not to view images.
  • It provides a semantic meaning and description to images which can be read by search engines or be used to later determine the content of the image from page context alone.

http://webaim.org/techniques/alttext/

You don't specify how you are outputting your html content and more specifically you images tags.

But I'm guessing, based on your question, that you have a html file with a lot of img tags, and you want to add an alt attribute where it's missing without the pain of doing it by hand.

If that's the case, the way to go is to parse your HTML file with PHP, and save the result to a new HTML file with all img tags containing the required alt tag.

You can read the HTML file content with the PHP method file_get_contents() .

Then parse the retrieved content with preg_replace() to detect img tags missing the alt attribute, and add them.

And finally save the parsed content with file_put_contents() back to a HTML file that you can use later on.

A PHP implementation could be :

// Retrieve the HTML content to be parsed
$html = file_get_contents( "path_to_html_file" );

// This regexp select all img tags not already containing an alt attribute
$pattern = '#<img(?!.*alt=")(.+src="(([^"]+/)?(.+)\..+)"[^ /]*)( ?\/?)>#i';

// Add alt attribute to img tags lacking it
// put the filename without extension as a value to the alt attribute
$parsed_html = preg_replace( $pattern, '<img$1 alt="$4"$5>', $html );

// Save the parsed content to a new file
file_put_contents( "path_to_parsed_html_file", $parsed_html );

This will get it done

jQuery(document).ready(function () {
  jQuery("img").each(function () {
    var img_src = jQuery(this).attr('src');
    if (typeof img_src !== typeof undefined && img_src !== false) {
      var img_alt = jQuery(this).attr('alt');
      var str = img_src
      var pieces = str.split('/');
      var imgName = pieces[pieces.length - 1];
      var imgnameArray = imgName.split('.');
      var alt = imgnameArray[0];
      if (img_alt == '' || typeof img_alt === typeof undefined || img_alt === false) {
        jQuery(this).attr('alt', alt);
      }
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM