1

I have fetched an HTML page,How i can replace relative img src with these URLs absolute?

In my content html:

<img width="23" height="23" class="img" src="/static/img/facebook.png" alt="Facebook">

<img width="23" height="23" class="img" src="/static/img/tw.png" alt="tw">

(Paths not stable)

<img width="130" =="" height="200" alt="" src="http://otherdomain/files/ads/00905819.gif">

in html contents i have other images src with absolute src,i want change only relative src images. ex :

  <img width="23" height="23" class="img" src="/static/img/facebook.png"    alt="Facebook">
  <img width="23" height="23" class="img" src="/images/xx.png" alt="xxx">

to

<img width="23" height="23" class="img" src="http://example.com/static/img/facebook.png" alt="Facebook">

My preg_replace:

$html = preg_replace("(]*src\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)", '$1http://www.example.com$2$3', $x1);

But this replace all images src

2 Answers 2

2

Try using this code, it should work in your case.

$html = str_replace('src="/static', 'src="http://example.com/static', $html);
Sign up to request clarification or add additional context in comments.

Comments

1

If you know that your relative path always starts with '/static/img/' then you can use simple str_replace function instead of regexp.

For example:

$html = str_replace('src="/static/img/', 'src="http://example.com/static/img/', $html);

1 Comment

Thanks,But path not stable

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.