简体   繁体   English

如果缺少图像文件名,如何使用 php 自动添加图像“alt”属性?

[英]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.我需要为数百张图片添加图片 alt 标签。 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:我已经能够使用 javascript 在某种程度上实现这一点,如下所示:

<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:然后 javascript 将像这样自动添加 alt:

<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.好吧,这一切都很好,但现在我想用 PHP 来代替,因为问题是这只是将标签添加到前端,这意味着它从页面源代码中不可见(仅检查元素) ,这意味着搜索引擎不会看到 alt 标记,这意味着唯一的方法是使用 php 将其直接放入页面中。

So how can I do my above javascript solution using php?那么如何使用 php 执行上述 javascript 解决方案呢?

Does the filename consistently provide a meaningful slug? 文件名是否始终提供有意义的slug? If not, you are better off just having empty alt tags. 如果没有,你最好只有空的alt标签。 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. Web爬虫已经获取了图像文件名,因此添加最后一位只有在它实际描述图像时才有用。 (It's also not 100% true it won't be indexed via JS, some bots, notably Google, do parse JavaScript to some degree.) (它也不是100%真实,它不会通过JS索引,一些机器人,特别是谷歌,在某种程度上解析JavaScript。)

If the filename is not descriptive, it's probably going to do more harm than good (for SEO and screen readers). 如果文件名不具有描述性,那么它可能会弊大于利(对SEO和屏幕阅读器而言)。 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? 我假设图像不是以某种方式进行内容管理,您可以从alt(和/或longdesc)属性的标题或描述中提取?

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/ http://webaim.org/techniques/alttext/

You don't specify how you are outputting your html content and more specifically you images tags. 您没有指定输出html内容的方式,更具体地说是图像标记。

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. 但我猜,根据你的问题,你有一个带有很多img标签的html文件,并且你想要添加一个alt属性,而不需要手工操作。

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. 如果是这种情况,那么可以采用PHP解析HTML文件,并将结果保存到包含所需alt标签的所有img标签的新HTML文件中。

You can read the HTML file content with the PHP method file_get_contents() . 您可以使用PHP方法file_get_contents()读取HTML文件内容。

Then parse the retrieved content with preg_replace() to detect img tags missing the alt attribute, and add them. 然后使用preg_replace()解析检索到的内容,以检测缺少alt属性的img标记,并添加它们。

And finally save the parsed content with file_put_contents() back to a HTML file that you can use later on. 最后将带有file_put_contents()的已解析内容保存回您稍后可以使用的HTML文件。

A PHP implementation could be : PHP实现可以是:

// 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);
      }
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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