我想将所有相对背景图像路径替换为绝对路径。在尝试了这么多时间之后,我未能解决这个问题。我当前的代码只解决了最后一个图像路径。我在此代码中使用了路径解析器函数(来自此参考:url_to_absolute())。
<?php
require './url_to_absolute.php';
$css = "
.selector1{
background-image:url(../dir1/images/image.jpg);
width:100%;
}
.selector2{
background-image:url(\"../dir1/images/image2.jpg\");
color:black;
}
.selector3{
background-image:url( 'dir1/images/image3.jpg' );
text-align:left;
}
.selector4{
background-image:url( \"dir1/images/image4.jpg\" );
text-align:left;
}
" ;
$base_url = 'http://www.example.com/';
$pattern = "/(?<=\()(.*?)(?=\))/s";
preg_match_all($pattern, $css, $matches);
foreach($matches[1] as $url){
$url = trim($url);
$url = str_replace("\"", "", $url);
$url = str_replace("'", "", $url);
$full_path = url_to_absolute($base_url, $url);
$new_css = str_replace($url, $full_path, $css);
}
print $new_css;
?>
它产生结果 -
.selector1{ background-image:url(../dir1/images/image.jpg); width:100%; }
.selector2{ background-image:url("../dir1/images/image2.jpg"); color:black; }
.selector3{ background-image:url( 'dir1/images/image3.jpg' ); text-align:left; }
.selector4{ background-image:url( "http://www.example.com/dir1/images/image4.jpg" ); text-align:left; }
请给我建议。