Page 1 of 1

img replace

Posted: Tue Mar 22, 2011 10:24 am
by pedroz
Having multiple image scenarios, need to find a regex to find an image and replace the full tag with other tag...

Code: Select all

$a = 'asdasdasd as asdasdas <img src="http://www.domain1.com/1.gif"> sdfsdf';
// or
$a = 'asdasdasd as asdasdas <img class="right" src=http://www.domain1.com/1.gif /> sdfsdf';
// or
$a = 'asdasdasd as asdasdas <img alt="image" src=http://www.domain1.com/1.gif> sdfsdf';
// or
$a = "asdasdasd as asdasdas <img width='10' height='10' src='http://www.domain1.com/1.gif' alt='as' /> sdfsdf";
// or
$a = preg_match('/(<img).*?src.*?(http://www.domain1.com/1.gif)/i>','<img src="http://www.domain2.com/11.gif">', $a);

var_dump($a);
// should be 'asdasdasd as asdasdas <img src="http://www.domain2.com/11.gif"> sdfsdf'
May you please improve my regex?

Thanks!

Re: img replace

Posted: Tue Mar 22, 2011 12:30 pm
by mikecampbell
Try this:

Code: Select all

$a = preg_replace('|<img ([^>]*)src="?http://www.domain1.com/1.gif"? ([^>]*)>|i','<img $1src="http://www.domain2.com/11.gif" $2>', $a);

Re: img replace

Posted: Wed Mar 23, 2011 6:01 pm
by pedroz
Hi Mike,

Thanks but it is not working :(

What I need is find the img tag with the src=http://www.domain1.com/1.gif (this tag can have many alternatives) and replace <img> tag with the following:
<img src="http://www.domain2.com/11.gif">

Something like this

Code: Select all

$a = preg_replace('|<img ([^>]*)src="?http://www.domain1.com/1.gif"? ([^>]*)>|i','<img src="http://www.domain2.com/11.gif">', $a);