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

agv*_*vr3 6 html php image attr alt

我需要为数百张图片添加图像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>
Run Code Online (Sandbox Code Playgroud)

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

<img src="http://mywebsite.com/images/the-image1.jpg" />
Run Code Online (Sandbox Code Playgroud)

那么javascript将自动添加alt,如下所示:

<img src="http://mywebsite.com/images/the-image1.jpg" alt="the-image1" />
Run Code Online (Sandbox Code Playgroud)

嗯,这一切都很好,但是现在我想用PHP代替它,因为问题是这只是将标签添加到前端,这意味着它从页面源不可见(只有inspect元素) ,这意味着搜索引擎将不会看到alt标记,这意味着唯一的方法是使用php将其直接放入页面.

那么如何使用php进行上述javascript解决方案呢?

Mat*_*sia 0

您不指定如何输出 html 内容,更具体地说是图像标签。

但我猜测,根据你的问题,你有一个包含很多img标签的 html 文件,并且你想添加一个alt缺少的属性,而无需手动操作。

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

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

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

最后将解析的内容保存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 );
Run Code Online (Sandbox Code Playgroud)