Kunwar Siddharth Singh
Kunwar Siddharth Singh

Reputation: 1676

Img tag replace in PHP

I have multiple img url like this this :-

<img alt="" border="0" src="http://asia.cnet.com/05/i/g/red_arrow_dn.gif">

And I want to replace every start up and close img tag like this in php:-

<div class="miricle_image"><img alt="" border="0" src="http://asia.cnet.com/05/i/g/red_arrow_dn.gif"/></div>

But I am unable to replace start up and close img tag through regex or preg_replace in php.

All img tag created by fckeditor and save in data base and my work is get all img tag through database and replace with

<div class=""><img src=""/></div> 

and save again in database.

Upvotes: 2

Views: 218

Answers (4)

Marcin Licznerski
Marcin Licznerski

Reputation: 380

Try using PHP HTML parser like: https://github.com/paquettg/php-html-parser and try replacing img node with wrapped one.

Upvotes: 0

Dilovan Matini
Dilovan Matini

Reputation: 86

try to test this code

<?php

$text = "<img src='abc.jpg'><img src='abc.jpg'><img src='abc.jpg'>";

$text = preg_replace("/<img([^>]*)>/i", '<div class="miricle_image"><img\\1></div>', $text);

echo $text;

?>

and demo here https://eval.in/178421

Upvotes: 0

Satish Sharma
Satish Sharma

Reputation: 9635

you can try this jquery

$("img").each(function(){
           var htm = $(this).html(); 
           htm = '<div class="miricle_image">'+htm+' div</div>';
           $(this).html(htm);  
    });

DEMO

Upvotes: 0

Nauphal
Nauphal

Reputation: 6192

Regular expression is not reliable in case of html parsing. It is better to use some html parser in php. simple html dom is a good parser, which is simple and very similar to jQuery. You can use this to manipulate html string from php

Upvotes: 1

Related Questions