PHP替换背景图像网址

时间:2018-01-05 08:22:22

标签: php css replace

我希望收到所有背景图片网址链接,并能够更改它们。例如,仅修改本地链接。

from this css:
#img1 { background-image: url('http://someurl.com/someimg.png'); }
#img2 { background-image: url('images/bg2.jpg'); }


to this css:
#img1 { background-image: url('http://someurl.com/someimg.png'); }
#img2 { background-image: url('somefolder/images/bg2.jpg'); } /* <- modified */

目前我只能更换所有网址,而不是检查本地网址:

$css = file_get_contents($file);
$css = str_replace('url("', 'url("'.$stringToAdd, $css);
file_put_contents($file, $css);

// not used
function isexternal($url) {
  $components = parse_url($url);    
  return !empty($components['host']) && strcasecmp($components['host'], 'example.com');
}

1 个答案:

答案 0 :(得分:1)

您可以使用preg_match_all功能:

$css = file_get_contents($file);
echo $css;
preg_match_all("/background-image: url\('(.*)'/", $css, $arr);
$images = $arr[1];
相关问题