我需要像这样转换一个 img:
<img src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" style="height:404px; width:602px" />
对此:
<amp-img src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" height="404" width="602"></amp-img>
请记住,此代码将位于具有更多 html 标记的代码的一部分中,重要的是,我不能使用任何库或任何东西..
我等待答案,提前谢谢!
您可以使用以下代码实现您的目标:
function html5toampImage($string) {
preg_match('/src="(.+?)"/', $string, $src);
$srcAttribute = $src[0];
preg_match('/style="(.+?)"/', $string, $styles);
$style = $styles[1];
$allData = explode(";",$style);
foreach($allData as $data) {
if($data) {
list($key,$value) = explode(":",$data);
if(trim($key)=="height") {
$heightAttribute = trim($key).'="'.trim(str_replace("px","",$value)).'"';
}
if(trim($key)=="width") {
$widthAttribute = trim($key).'="'.trim(str_replace("px","",$value)).'"';
}
}
}
$ampImageTag = '<amp-img '.$srcAttribute.' '.$heightAttribute.' '.$widthAttribute.' layout="responsive"></amp-img>';
return $ampImageTag;
}
$html5Tag = '<img alt="aa" src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" style="height:404px; width:602px; color:red" />';
echo htmlentities(html5toampImage($html5Tag));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句