Main Content

Adding retrospective ALT attributes to IMG

Archive - Originally posted on "The Horse's Mouth" - 2009-12-28 06:19:09 - Graham Ellis

You'll find this is article number 2554 on this blog ... with article number 1 written as long ago as 5th August 2004. I didn't plan that I would still be writing five years later (I thought, to be frank, that I would run out of things to say in a few weeks), nor did I properly anticipate the amount of traffic that would arrive at our web site through the archives.

Hindsight is marvellous, and with hindsight I would have included "alt" attributes with each image. That is so that the search engines know what the pictures show, and so that users for whom graphics are not suitable are offered an alternative. But I didn't start off with such attributes and, thousands of posts later, they're difficult to go back and add. However, in the intervening time I have also moved on to hold newly added images in a database, and as well as the data, each row includes a description which *has* been updated over the years to say what the picture's about.

So the archives - which you can access via our archive pages or via our global index - will not include that alternative text tag - going right back through all the images that are in the database.

The code is in PHP, of course ... and the "headline code" that's within the archive generator is as short as:

$ret = preg_replace('/<img\s+(.*?)>/e',
  "'<img '.add_alt('\1').'>'",
  $row[entry_text]);


That, though, is just a half of the story - the add_alt function that is called on each match looks something like this:

function add_alt($attribs) {
if (preg_match('!alt=!',$attribs)) {
  $rval = $attribs;
} else {
  if (preg_match('!src="?http://www.wellho.net/pix/(\S+)!',$attribs,$matches)) {
    $name = trim($matches[1],'"');
    $rs = @mysql_query ("select filename, descriptor from im_library where filename = \"$name\"");
    $dbk = @mysql_fetch_assoc($rs);
    $nst = "";
    if ($dbk) {$nst = htmlspecialchars($dbk[descriptor]);}
    $rval = "$attribs alt=\"$nst\"";
  } else {
    $rval = $attribs;
  }
}
return ($rval);
}


If you're wondering what on earth the picture at teh top of this article is, and you view source on my daily blog ... you won't be given much of a clue. But if you have a look at the archive here, then the ALT tag will give you, and the search engines, the clues you're likely to be seeking.





Is it still worthwhile, five years on, me writing these tecnical tips? Yes ... I have just been reviewing my user feedback and here are some of the recent unedited comments made:

REALLY A FANTASTIC ARTICLE

Very good explainaiton. Simple and to the point..

Well,it is working good,Thanks for your great work... Thanks Ramakrishnan

I really got helped. These are pure basics of joining which are base of database.

perfect explanation. I can't believe it's that easy. Thank you!

Thanks a lot for the info.Really recommandable job done.