preg_replace to add something after closing tag – PHP

PHP – preg_replace to add something after closing tag :

Here i will explain how to add something like string, char (or) any html tag after closing tag. Here we are using preg_replace() function to do it.

In the below example, add <br /> tag after closing of all <img> tag.

Syntax :

    preg_replace('/(<img[^>]+>(?:</img>)?)/i', '$1<br />', $str);
    
Note : This will match with <img />, <img>, <img></img> all of it.

Example :

    <?php
    
        $str = "<img src='img_path'>TechniqZone<img src='img_path'>";
        echo preg_replace('/(<img[^>]+>(?:</img>)?)/i', '$1<br />', $str);
        
    ?>

    
Output :

    <img src='img_path'><br />TechniqZone<img src='img_path'><br />
    
You can use this preg_replace() syntax for any of the html tags.

Leave a Reply

Your email address will not be published. Required fields are marked *