从HTML内容替换图像src属性

时间:2016-10-26 18:08:30

标签: php

我制作了一个Chrome扩展程序,用于读取页面内容并将其发布到我的网络服务器。问题是我需要将src属性从html源更改为我的网站地址。

让我们去看我的代码(这只是一个例子):

$html = '<p style="font-size: 12px; font-family: Tahoma; text-align: center;"><img style="font-size: 12px; font-family: Tahoma;" src="http://sga.ufmg.br/images/uploads/13212/MSI_civil_01.png" alt="" width="338" height="367"></p>';

$img = 'http://sga.ufmg.br/images/uploads/13212/MSI_civil_01.png';

$result = str_replace($img, 'http://asrespostazzz.com.br/questoes_img/' . $new_img_name, $html);

它根本无法工作.... :(

我尝试使用preg_replace,但给了我一个错误:

  

消息:preg_replace()[function.preg-replace]:分隔符不能是字母数字或反斜杠

1 个答案:

答案 0 :(得分:-1)

如果你的html中有单个图像元素,那么preg_replace将起作用:

preg_replace('/<img\ [^>]+src="([^"]+)"/', 'http://asrespostazzz.com.br/questoes_img/' . $new_img_name, $html);

但是如果你有多个图像元素,那么你必须构建一个带有替换的数组(我不知道它是否适合你的情况......更多信息会有所帮助)。因此,您的preg_replace代码将如下所示:

$replacements = [
      'http://asrespostazzz.com.br/questoes_img/' . $new_img_name,
      .....
];
preg_replace('/<img\ [^>]+src="([^"]+)"/', $replacements, $html);