Last active
August 27, 2021 12:33
-
-
Save elalemanyo/034490164beb7b935559585ff1cc7d9f to your computer and use it in GitHub Desktop.
Make img AMP-ready
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, $img_matches); | |
foreach ($img_matches[1] as $key => $img_tag) { | |
preg_match_all('/(alt|src|width|height)=["\'](.*?)["\']/i', $img_tag, $attribute_matches); | |
$attributes = array_combine($attribute_matches[1], $attribute_matches[2]); | |
if (!array_key_exists('width', $attributes) || !array_key_exists('height', $attributes)) { | |
if (array_key_exists('src', $attributes)) { | |
list($width, $height) = getimagesize($attributes['src']); | |
$attributes['width'] = $width; | |
$attributes['height'] = $height; | |
} | |
} | |
$amp_tag = '<amp-img '; | |
foreach ($attributes as $attribute => $val) { | |
$amp_tag .= $attribute .'="'. $val .'" '; | |
} | |
$amp_tag .= 'layout="responsive"'; | |
$amp_tag .= '>'; | |
$amp_tag .= '</amp-img>'; | |
$html = str_replace($img_matches[0][$key], $amp_tag, $html); | |
} | |
return $html; | |
} |
@hardeep360 @saosangmo
Sorry but I don't see any error, I test your example string and works for me. Maybe I am missing something?
$str = "<img class='avia_image' src='https://abc.com/abc.jpg' alt='Liquidaromen' title='Liquidaromen' itemprop=\"contentURL\" width=\"100\" height=\"100\" />";
print _ampify_img($str);
<amp-img src="https://abc.com/abc.jpg" alt="Liquidaromen" width="100" height="100" layout="responsive"></amp-img>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Syntax error, please update and correct quotes.