[英]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 來代替,因為問題是這只是將標簽添加到前端,這意味着它從頁面源代碼中不可見(僅檢查元素) ,這意味着搜索引擎不會看到 alt 標記,這意味着唯一的方法是使用 php 將其直接放入頁面中。
那么如何使用 php 執行上述 javascript 解決方案呢?
文件名是否始終提供有意義的slug? 如果沒有,你最好只有空的alt標簽。 Web爬蟲已經獲取了圖像文件名,因此添加最后一位只有在它實際描述圖像時才有用。 (它也不是100%真實,它不會通過JS索引,一些機器人,特別是谷歌,在某種程度上解析JavaScript。)
如果文件名不具有描述性,那么它可能會弊大於利(對SEO和屏幕閱讀器而言)。 如果您計划使用此方案,我假設您要么或將要提供描述性文件名。
我假設圖像不是以某種方式進行內容管理,您可以從alt(和/或longdesc)屬性的標題或描述中提取?
如果它是一次性修復,再次取決於命名的質量,它可能沒問題。 幾百張圖片可能不會花那么長時間,並且總是[廣告被刪除] :)
替代文本有幾個功能:
- 它由屏幕閱讀器代替圖像讀取,允許具有視覺或某些認知障礙的人可以訪問圖像的內容和功能。
- 如果未加載圖像文件或用戶選擇不查看圖像,則在瀏覽器中顯示該圖像。
- 它為圖像提供語義含義和描述,可以由搜索引擎讀取,或者用於稍后僅從頁面上下文確定圖像的內容。
您沒有指定輸出html內容的方式,更具體地說是圖像標記。
但我猜,根據你的問題,你有一個帶有很多img
標簽的html文件,並且你想要添加一個alt
屬性,而不需要手工操作。
如果是這種情況,那么可以采用PHP解析HTML文件,並將結果保存到包含所需alt
標簽的所有img
標簽的新HTML文件中。
您可以使用PHP方法file_get_contents()讀取HTML文件內容。
然后使用preg_replace()解析檢索到的內容,以檢測缺少alt
屬性的img
標記,並添加它們。
最后將帶有file_put_contents()
的已解析內容保存回您稍后可以使用的HTML文件。
// 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);
}
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.