我正在使用ampify_img将常规图像标签转换为 amp 图像标签。所以:
<img src="dir/whatever/photo.jpg" alt="Whatever">
转换为:
<amp-img src="dir/whatever/photo.jpg" layout="responsive" class="i-amphtml-element"></amp-img>
问题是:要成为放大器宽度和高度的有效标记,必须在此转换后的标签中设置。而且我不知道如何将 src 提取到转换图像并写入新标签的函数中。我知道我可以使用 PHP getimagesize() 获取图像大小,但无法弄清楚它在哪里。我不擅长正则表达式,这可能会使实现目标变得更加困难。
放大默认图像功能:
<?php
/**
* Replace img tag with amp-img
*
* <amp-img src="[src]"
* width="[width]"
* height="[height]"
* layout="responsive"
* alt="[alt]">
* </amp-img>
*
*/
function ampify_img ($html) {
preg_match_all("#<img(.*?)\\/?>#", $html, $matches);
foreach ($matches[1] as $key => $m) {
preg_match_all('/(alt|src|width|height)=("[^"]*")/i', $m, $matches2);
$amp_tag = '<amp-img ';
foreach ($matches2[1] as $key2 => $val) {
$amp_tag .= $val .'='. $matches2[2][$key2] .' ';
}
$amp_tag .= 'layout="responsive"';
$amp_tag .= '>';
$amp_tag .= '</amp-img>';
$html = str_replace($matches[0][$key], $amp_tag, $html);
}
return $html;
}
我试图从 $matches2[2][$key2] 或 $matches2[2] 或 $matches 中提取 getimagesize() 没有成功。我认为比其他任何事情都更了解从何处提取信息以写入 $amp_tag。
<?php
// comments where i tried to get info
function ampify_img ($html) {
preg_match_all("#<img(.*?)\\/?>#", $html, $matches);
foreach ($matches[1] as $key => $m) {
preg_match_all('/(alt|src|width|height)=("[^"]*")/i', $m, $matches2);
$amp_tag = '<amp-img ';
foreach ($matches2[1] as $key2 => $val) {
$amp_tag .= $val .'='. $matches2[2][$key2] .' '; // guess it can be here and possibly width and height can be writed here
}
$amp_tag .= 'layout="responsive"'; // certainly width and height can be writed here if we can get each image src at conversion and call PHP getimagesize
$amp_tag .= '>';
$amp_tag .= '</amp-img>';
$html = str_replace($matches[0][$key], $amp_tag, $html);
}
return $html;
}
波斯汪