1
votes

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

2 Answers

2
votes

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

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

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