Search code examples
phpgoogle-amp

How can I replace <img> tags in HTML with <amp-img> tags?


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.


Solution

  • 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">'
    ));