Skip to content

Instantly share code, notes, and snippets.

@laocoi
Forked from elalemanyo/ampify_img.php
Created March 23, 2018 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laocoi/1fce603f5acf2e2cdf8b52d11990d26f to your computer and use it in GitHub Desktop.
Save laocoi/1fce603f5acf2e2cdf8b52d11990d26f to your computer and use it in GitHub Desktop.
Make img AMP-ready
<?php
/**
* Replace img tag with amp-img
*
* <amp-img src="[src]"
* width="[width]"
* height="[height]"
* layout="responsive"
* alt="[alt]">
* </amp-img>
*
*/
function _domradio_util_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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment