Subscribe For Free Updates!

We'll not spam mate! We promise.

Showing posts with label php preg replace. Show all posts
Showing posts with label php preg replace. Show all posts

Aug 26, 2014

preg_replace to add something after closing tag - PHP

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.