1

In PHP, I use this pattern to append absolute paths to relative URLs in my CSS file:

$sCssR = preg_replace('#url\((?!\s*[\'"]?(?:https?:)?//)\s*([\'"])?#', "url($1{$sRel}/", $sCss);

The pattern is working well, but data URLs like SVG images are effected too.

Example:

<? ob_start(); ?>
.url { background:url("//www.test.com/img.png"; }
.url { background:url("http://www.test.com/img.png"; }
.url { background:url("../img/test.png"; }
.url { background:url("data:image/svg+xml;utf8,<svg><circle/></svg>"); }
<?
    $sCss = ob_get_clean();
    $sRel = '//www.test.com/folder';
    $sCssR = preg_replace('#url\((?!\s*[\'"]?(?:https?:)?//)\s*([\'"])?#', "url($1{$sRel}/", $sCss);
    print $sCssR;
?>

Output will be:

.url { background:url("//www.test.com/img.png"; }
.url { background:url("http://www.test.com/img.png"; }
.url { background:url("//www.test.com/folder/../img/test.png"; }
.url { background:url("//www.test.com/folder/data:image/svg+xml;utf8,<svg><circle/></svg>"); }

Everything is fine, except the last line, which should not be touched and should look like this:

.url { background:url("data:image/svg+xml;utf8,<svg><circle/></svg>"); }

Can anyone help me to adjust the preg_replace pattern so 'data:' URLs won't be touched?

0

1 Answer 1

1

Add a trailing (*SKIP)(*FAIL) component to the end of your pattern:

~url\((?!\s*[\'"]?(?:https?:)?//)\s*([\'"])?(?:data:(*SKIP)(*FAIL)|)~

(Pattern Demo)

This will effectively "disqualify" urls as you expect.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice, thx! Btw. do you know the difference between using '#url...#' and '~url...~' in the pattern? Both is working,
There is no difference in this case. Because you aren't using # or ~ inside the pattern itself. Choosing the best pattern delimiter comes down to selecting a valid delimiter that will not be used in your pattern. (~ just happens to be my 1st preference after /) If you choose a pattern delimiter that also occurs inside the pattern itself, then it must be escaped -- this impacts pattern brevity and readability, so I avoid escaping whenever possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.