Search code examples
phpregexamp-html

Convert HTML5 img to AMP amp-img with attribute conversion


I need to convert an img like this:

<img src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" style="height:404px; width:602px" />

to this:

<amp-img src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" height="404" width="602"></amp-img>

Keeping in mind that this code will be in a portion of code with more html tags and, important, I can't use any library or anything..

I await answers, thanks in advance!


Solution

  • You can Achieve your goal with following code :

    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));
    

    Here is working eval url