Php Replace Img tag by amp-img


Php Replace Img tag by amp-img– We can use regular expression and str_replace to replace image tag by amp image tag.


Php Replace Img tag by amp-img | AMP image tag Example

You can use the below example to replace image tag by amp-img tag-

Php Replace Img tag by amp-img | Example:

<?php
$content = "Hello Welcome to Tutorialsplane <img src='abc.png' alt='AMP Example' height='200'width='300' >. Learn more";
$result = preg_replace('/(<img[^>]+>(?:<\/img>)?)/i', '$1</amp-img>', $content);
echo str_replace('<img', '<amp-img', $result);
?>

The above example will take care about height width and alt tag of amp-img so you do’nt need to worry about anything.

Example 2 Using preg_replace

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

Advertisements

User Ans/Comments

Thank you so much.You save my time :-) love you dear
 pavan
Great Article Worked like charm!!
 manu

Add Comment

📖 Read More