首页 文章

用完整的url php替换相对src img

提问于
浏览
-1

我已经获取了一个HTML页面,我如何用这些URL绝对替换相对img src?

在我的内容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">

(路径不稳定)

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

在HTML内容我有其他图像src与绝对src,我想只更改相对src图像 . 例如:

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

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

我的preg_replace:

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

但这取代了所有图像src

2 回答

  • 1

    如果您知道您的相对路径始终以 '/static/img/' 开头,那么您可以使用简单的 str_replace 函数而不是regexp .

    例如:

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

    尝试使用此代码,它应该适用于您的情况 .

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

相关问题