2

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

1
  • Your pattern needs delimiters. Commented Aug 5, 2012 at 11:47

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

1 Comment

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/logosThis Part Changes constantly, so I need preg_replace instead of str_replace.jpg"','src="mywebsite.com/default.gif"',$content);
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.