0

我想将所有相对背景图像路径替换为绝对路径。在尝试了这么多时间之后,我未能解决这个问题。我当前的代码只解决了最后一个图像路径。我在此代码中使用了路径解析器函数(来自此参考: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; } 

请给我建议。

4

1 回答 1

1

虽然我很欣赏公认的答案,但它可能是我在 PHP 中见过的最复杂的函数之一......

这个更容易掌握(根据您的需要调整正则表达式):

function urlsToAbsolute($baseUrl, $html) {

    preg_match_all('/(href="|src=")([^"#]+)(")/i', $html, $matches);

    foreach ($matches[2] as $num => $match) {
        $codec[$match] = url_to_absolute($baseUrl, $match);
    }

    return strtr($html, $codec);
}
于 2013-07-29T11:32:17.887 回答