CSS属性

时间:2015-06-30 01:09:10

标签: php html regex preg-replace

我使用file_get_contents()获取网页的源代码,但在某些使用CSS的网站中我失败了:

background: url("/media/image")
background: url(/media/image)
background: url('/media/image')
// etc...

现在,我想知道如何编辑CSS并添加我的网站,所以它看起来像这样:

background: url("http: //example.com/media/image")
background: url('http: //example.com/media/image')
background: url(http://example/media/image)
// etc...

。这是我的代码:

$regex = "-(src\s*=\s*['\"])(((?!'|\"|http://|https://|//).)*)(['\"])-i"; 

我是在HTML标记的src属性上执行此操作。我希望我能帮助

1 个答案:

答案 0 :(得分:2)

$regex会将background: url(["|']?$URL["|']?)替换为["|']?$img["|']?

$homepage = file_get_contents('http://www.example.com/');
$img = "http://placehold.it/350x150";

$regex = '/(background: url\((["|\']?))(.+)(["|\']?\))/';
$replacement = "$1$img$4";
$homepage = preg_replace($regex, $replacement, $homepage);

echo $homepage;