如何用<amp-img>标签替换HTML中的<img>标签? [重复]

This question already has an answer here:

I want to turn HTML pages into Google AMP pages, and I have this problem where I have a lot of <img> that I want to turn into <amp-img> tags.

For example, I want to turn:

<img src='apa.png'><br>
hi bro <img src="c.png'>

into something like this:

<amp-img src="apa.png" width="800" height="684" layout="responsive" alt="AMP"></amp-img><br/>
hi bro <amp-img src="c.png" width="800" height="684" layout="responsive" alt="AMP"></amp-img>

I've tried to replace those tags with PHP, but it didn't work.

</div>

You can use preg_replace to replace a pattern with a string (http://php.net/manual/en/function.preg-replace.php).

Try this code:

echo htmlentities(preg_replace(
    '/<img src="([^"]*)"\s*\/?>/', 
    '<amp-img src="$1" width="800" height="684" layout="responsive" alt="AMP"></amp-img>', 
    '<img src="apa.png"><br>hi bro <img src="c.png">'
));

If this HTML is present on the HTML file, then all you need to do is do search-replace <img src= with <amp-img width="800" height="684" layout="responsive" alt="AMP" src=

if you have a editor that is capable of finding and replacing using regular rexpression, use the following regex on FIND:

 <img src=("|')(.*)'>

and following on REPLACE:

<amp-img src="$2" width="800" height="684" layout="responsive" alt="AMP"</amp-img>

I tried this with Dreamwearver and it worked for me.

I was just in a situation where I need to change all image tags in one meta field (a WordPress custom WYSIWYG field) and I thought this may help others. This code is basically a combination of some of the responses posted here, modified slightly, as the <img> tags had extra info in them before the src:

   echo preg_replace(
        '/<img .*? src="([^"]*)" .*?>/', 
        '<amp-img src="$1" width="600" height="600" layout="intrinsic" alt="AMP"></amp-img>', 
        $meta_field_output
    );

After a while testing regexs, i found an solution that matched my needs,

return preg_replace_callback('/<img[\s*]alt="([^"]*)"[\s*]src="([^"]*)"([\s*]?)((.*?)+?)>/',
function ($found) {
    $size = (getimagesize($found[2]));

    return '<amp-img src="' . $found[2] . '" width="'. $size[0] .'" height="' . $size[1] . '" layout="responsive" alt="' . $found[1] .'"></amp-img>';
}, $html);