I merge some CSS files and write them to a file in a separate directory. I am trying to replace relative url() values to work with a new file location, ignoring absolute URLs. Here is a CSS example:
#TEST { background:url(test.jpg); background:url( 'test.jpg' ); background:url("test.jpg" ); background:url(http://example.com/test.jpg); background:url('https://example.com/test.jpg'); background:url("http://example.com/test.jpg"); background:url( '//example.com/test.jpg' ); background:url( "//example.com/test.jpg" ); background:url(//example.com/test.jpg); }
Everything that does not start with http:// , https:// or // should get $path in front of it (only the first 3 must match).
Desired conclusion:
#TEST { background:url(/themes/default/css/test.jpg); background:url( '/themes/default/css/test.jpg' ); background:url("/themes/default/css/test.jpg" ); background:url(http://example.com/test.jpg); background:url('https://example.com/test.jpg'); background:url("http://example.com/test.jpg"); background:url( '//example.com/test.jpg' ); background:url( "//example.com/test.jpg" ); background:url(//example.com/test.jpg); }
However, this code corresponds to the opposite:
$path = '/themes/default/css/'; $search = '#url\(\s*([\'"]?)((http(s)?:)?//)#'; $replace = "url($1{$path}$2"; $css = preg_replace($search, $replace, $css);
I know that you can use something like !^(http) to not match lines starting with http , but everything I tried failed (I === bad in regex). I use the online regexp tester to figure this out, but really stuck.
This may not be what I'm using to solve the real problem (make sure the paths work in compiled CSS), but can someone help me fix this problem with regex or have a better solution?
Wesley murch
source share