如何自动添加图像“;alt”;属性使用image filename(如果缺少),则使用php


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

我需要为数百个图像添加一个图像alt标记。问题是,这将需要很长时间,无论如何,似乎有一个更容易的解决方案。

我已经能够使用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>

这正是我想要的,例如,如果我有这个图像:

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

然后javascript将自动添加alt,如下所示:

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

好吧,这一切都很好,但现在我想用PHP来做,因为问题是,这只是将标记添加到前端,这意味着它在页面源中不可见(只有inspect元素),这意味着您的搜索引擎看不到alt标记,也就是说,唯一的方法是使用PHP将其直接放入页面。

那么,我如何使用php来实现上述javascript解决方案呢?

文件名是否始终提供有意义的段塞?如果没有,你最好只使用空的alt标签。网络爬虫已经获取了图像文件名,所以添加最后一位只会在它实际上是对图像的描述时有所帮助。(这也不是100%正确的,它不会通过JS进行索引,一些机器人,尤其是谷歌,确实在一定程度上解析了JavaScript。)

如果文件名不是描述性的,它可能弊大于利(对于SEO和屏幕阅读器)。如果您计划继续使用此方案,我假设您正在或将提供描述性文件名。

我假设这些图像不是以某种方式进行内容管理的,你可以从alt(和/或longdesc)属性的标题或描述中提取这种方式吗?

如果这是一次性修复,同样取决于命名的质量,它可能还可以。几百张图像可能不会花那么长时间,而且总是有[广告删除]:)

替代文本具有多种功能:

  • 通过屏幕读取代替图像的阅读器允许具有视觉或特定认知能力的人可以访问的图像残疾
  • 如果图像文件未加载或用户选择不查看时图像
  • 它为图像提供了语义和描述可以由搜索引擎读取或用于稍后确定仅来自页面上下文的图像内容

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

您没有指定如何输出html内容,更具体地说,您没有指定图像标记。

但我猜,根据您的问题,您有一个包含大量img标记的html文件,并且您希望在缺少alt属性的地方添加它,而无需手动操作。

如果是这种情况,那么方法就是用PHP解析HTML文件,并将结果保存到一个新的HTML文件中,该文件中的所有img标记都包含所需的alt标记。

您可以使用PHP方法file_get_contents()读取HTML文件内容。

然后使用preg_replace()解析检索到的内容,以检测缺少alt属性的img标签,并添加它们。

最后,使用file_put_contents()将解析后的内容保存回HTML文件中,以便以后使用

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

这将完成

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

我使用此函数将$content:中所有没有alt或为空的图像替换为filenname

 $content = preg_replace_callback('~<img(.*?)>~', function ($matches) { //Search for all images
        if (!preg_match('~alt="'S+"~', $matches[1])) { // if alt with any characters not exists
            $img = preg_replace('~alt="'S*"~', '', $matches[0]); // remove empty alt
            preg_match('~src="(?:(?:[^"]+/)?(.+)'..+)"~', $img, $src); // get filename from src
            $alt = preg_replace('~-|_~', ' ', $src[1]); //replace '-' and '_' symbols with space symbol
            return preg_replace('~<img~', '<img alt="' . $alt . '"', $img); // put new alt into tag
        } else {
            return $matches[0];
        }
    }, $content);