2

I am trying to find a regex to convert relative url in css code 'url()'. So far this is what I have:

$domain = "http://example.com/";
$html = "url(1.css), url(' 1.css'), url( \"1.css\")";

$rep['/url(\s*)\((\s*)"(\s*)(?!https?:\/\/)(?!data:)(?!#)/i'] = 'url("'.$domain;
$rep["/url(\s*)\((\s*)'(\s*)(?!https?:\/\/)(?!data:)(?!#)/i"] = "url('".$domain;

$html = preg_replace(
    array_keys($rep),
    array_values($rep),
    $html
);
echo $html;

Current Output:

url(1.css), url('http://example.com/1.css'), url("http://example.com/1.css")

Desired Output:

url(http://example.com/1.css), url('http://example.com/1.css'), url("http://example.com/1.css")
4
  • you can save only one entry in replace array $rep['/url(\s*)\((\s*)["\']?(\s*)(?!https?:\/\/)(?!data:)(?!#)/i'] = 'url("'.$domain; Commented Apr 17, 2017 at 11:13
  • @spash58, this will give url("example.com/1.css), url("example.com/1.css'), url("example.com/1.css"). Notice that " appear in all cases. Commented Apr 17, 2017 at 11:21
  • exclusively for fun :) - with one expression eval.in/777666 Commented Apr 17, 2017 at 12:04
  • @splash58, You did it! Commented Apr 17, 2017 at 13:51

1 Answer 1

1

Are you expecting this? Hope it will work fine.

Try this code snippet here

Regex: /url[\s]*\([\s]*(?!'|\")(?!https?:\/\/)(?!data:)(?!#)

Here this regex will match url ( and after that there will be no " or '.

<?php
ini_set('display_errors', 1);
$domain = "http://example.com/";
$html = "url(1.css), url(' 1.css'), url( \"1.css\")";
$rep['/url[\s]*\([\s]*"[\s]*(?!https?:\/\/)(?!data:)(?!#)/i'] = 'url("'.$domain;
$rep["/url[\s]*\([\s]*'[\s]*(?!https?:\/\/)(?!data:)(?!#)/i"] = "url('".$domain;
$rep["/url[\s]*\([\s]*(?!'|\")(?!https?:\/\/)(?!data:)(?!#)/i"] = "url(".$domain;

$html = preg_replace(
    array_keys($rep),
    array_values($rep),
    $html
);
echo $html;
Sign up to request clarification or add additional context in comments.

Comments

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.