【问题标题】:replace relative src img with full url php用完整的 url php 替换相对的 src img
【发布时间】:2017-06-18 02:35:55
【问题描述】:

我已经获取了一个 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

【问题讨论】:

    标签: php regex


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果您知道您的相对路径总是以'/static/img/' 开头,那么您可以使用简单的str_replace 函数而不是正则表达式。

      例如:

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

      【讨论】:

      • 谢谢,但路径不稳定
      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 2016-06-03
      • 2016-04-28
      • 2012-07-03
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多