当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How can I replace all relative image path into absolute path form a css

问题描述:

I want to replace all relative background-image path into absolute path. After trying that so much time, I've failed to solve this. My current code only solves the last image path. I'm using a path resolver function(from this reference:url_to_absolute())in this code.

<?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;

?>

It generates the result -

.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; }

Advice me please.

网友答案:

While I appreciate the accepted answer for its cleverness, it might be one of the most complex function that I've seen in PHP...

This one if much easier to grasp (adapt regex to your needs):

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);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: