img replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pedroz
Forum Commoner
Posts: 99
Joined: Thu Nov 03, 2005 6:21 am

img replace

Post 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!
mikecampbell
Forum Commoner
Posts: 38
Joined: Tue Oct 12, 2010 7:26 pm

Re: img replace

Post 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);
pedroz
Forum Commoner
Posts: 99
Joined: Thu Nov 03, 2005 6:21 am

Re: img replace

Post 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);
Post Reply