Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 通过属性转换将HTML5 img转换为AMP img_Php_Regex_Amp Html - Fatal编程技术网

Php 通过属性转换将HTML5 img转换为AMP img

Php 通过属性转换将HTML5 img转换为AMP img,php,regex,amp-html,Php,Regex,Amp Html,我需要像这样转换一个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">&l

我需要像这样转换一个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));
函数html5toampImage($string){
preg_match('/src=“(.+?)“/”,$string,$src);
$srctattribute=$src[0];
preg_match('/style=“(.+?)”/”,$string,$styles);
$style=$style[1];
$allData=explode(“;”,$style);
foreach($allData作为$data){
如果($数据){
列表($key,$value)=分解(“:”,$data);
如果(修剪($key)=“高度”){
$heightAttribute=trim($key)。'=''。trim(str_replace(“px”),“”,$value))。';
}
如果(修剪($key)=“宽度”){
$widthAttribute=trim($key)。“=”。trim(str_replace(“px”),“,$value))。”;
}       
}
}

$ampImageTag='

如果段落之间有图像,该怎么办?我是指新闻网站,它包含文本之间的图像。