2
votes

I am trying to replace an Image URL which changes constantly.

Image URL: src="/images/previews/logo-15-hp.jpg". In this URL logo-15-hp.jpg will be changing every day to something else. What I am trying to do is replace this URL to a default one like this: src="http://mywebsite.com/images/previews/default.jpg".

I tried doing this with preg_replace, but I am unable to make it work. I tried different variations and finally gave up. I would be glad if someone could help me with this.

My Code:

$content = 
preg_replace('src="/images/previews/logo\-15\-hp\.jpg"','src="http://mywebsite.com/default.gif"',$content);

I also tried this:

preg_replace('src\=\"\/images\/previews\/logo\-15\-hp\.jpg\"','src="http://mywebsite.com/default.gif"',$content);

Also please explain any code you suggest. It will help me in future.

Thanks!

Edit: I am trying to automatically detect the URL and change, but I can't even do it with full URL in preg_replace. For instance I need a code like this:

$content = preg_replace('src="/images/previews/logos***This Part Changes constantly, so I need preg_replace instead of str_replace***.jpg"','src="http://mywebsite.com/default.gif"',$content);

2
Your pattern needs delimiters. - rexmac

2 Answers

2
votes

Here is what you need to do

$content = preg_replace(
    '#src="/images/previews/logos[^"]+#',
    'src="http://mywebsite.com/default.gif"',
    $content
);

This will replace anything after '/logos' up till it finds a double quote.

Edit: Updated response per updated question...

0
votes

It will surely help you. I have tested then posted it. Plz see the code attached:

$content = 'hello this is content<img  src="/images/previews/logo-15-hp.jpg" height="50"
width="50" alt="image" />content after image';
$pattern = '/\/images\/previews\/logo\-15\-hp\.jpg/';
$replacement = 'http://mywebsite.com/images/previews/default.jpg';
$final_content = preg_replace($pattern, $replacement, $content);
echo $final_content;