简体   繁体   中英

Regular Expression to Convert Relative URLs to Absolute URLs in CSS

I am combining multiple CSS files into one (the hierarchy of the CSS files is variant), so I need to convert relative URLs in CSS files to absolute URLs.

Below is the requirement;

CSS file URL: http://example.com/template/default/css/style.css
Domain: http://example.com

Input

#test {
    background:url(../images/test.jpg);
    background:url( 'test.jpg' );
    background:url("../../common/test.jpg"  );
    background:url(http://example.com/test.jpg);
    background:url('https://example.com/test.jpg');
    background:url( '//example.com/test.jpg' );
    background:url( "//example.com/test.jpg" );
    background:url(//example.com/test.jpg);
}

Required Output

#test {
    background:url(http://example.com/template/default/images/test.jpg);
    background:url( 'http://example.com/template/default/css/test.jpg' );
    background:url("http://example.com/template/common/test.jpg"  );
    background:url(http://example.com/test.jpg);
    background:url('https://example.com/test.jpg');
    background:url( '//example.com/test.jpg' );
    background:url( "//example.com/test.jpg" );
    background:url(//example.com/test.jpg);
}

Please note the ../ and ../../ for relative paths.

I have tried the similar solutions from preg_replace() regex to match relative url() paths in CSS files but that're a different and I am not getting it to work for my situation.

Thanks in advance for help.

The solution is very simple. If you want to load any file, image, etc. on an HTML page, you must use / so any URL will be domain.com/URL .

Your CSS should be:

#test {
    background:url(/test.jpg);
    background:url(/template/default/images/test.jpg);
}

This works for any file: CSS, JS file, Link in <a> tag, etc.


EDIT

So, you must use php to do this. I recommend you to create your own function/class that reads the root path of the file (here would be http://example.com/template/default/css/ ) and then explode the path you give, if you recive .. go back one folder (delete css/ in this case) and the add the other parts that are not .. .

Really simple and straight-forward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM