1

hello I want to replace this code of css:

background:url("/media/image.png")

and I have a url

$url3 ="http://example.com";

here is the code I'm using :

preg_replace('~url\(("|\')?/?(.*?)(?:\1)?\)~', 'url($1'.$url3.'/$2$1)', background:url("/media/image.png");

the output of this code gives me :

background:url("http://example.com/media/image.png") 

and this is what I want , but my problem is I want to add some conditions to my regex for example if the url have // or http or https at start then ignore it don't add http://example.com/ to it.

this is the regex I have tried :

~url\(("|\')?/?(.*?)(?:\1)?\)~(((?!'|\"|http://|https://|//).)*)(['\"])-i 

but it didn't work ..

  • maybe use parse_url() http://php.net/manual/en/function.parse-url.php – Robert Jun 30 '15 at 15:24
  • This is your third question on this topic in the past 24 hours. Why not leave one open and explain your question. State **exactly** what you are trying, what you have, and what you want? – chris85 Jun 30 '15 at 15:24

3 Answers3

0

Since you are hard-coding the replacement I think it would be easiest to just do another check:

if (false === preg_match("~url\((\"|')(//|https?://)~", $string)) {
    // do replacement
}

Also note that the argument to url() in CSS does not require quoting (" or ').

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

This can be done using a negative look around:

url\(("|\')((?!http://|https://).*?)(?:\1)\)

You can watch it in action here.

Check out this question for more info.

Community
  • 1
  • 1
Anders
  • 8,307
  • 9
  • 56
  • 88
0

Check

$string = preg_replace(
    '/url\(("|\')(?!https?)\/?(.+?)(?:\1)/',
    'url(\1http://example.com/$2\1',
    $string
)
  • Please consider adding at least some words to your code snippet explaining why and how it does answer the OP question – β.εηοιτ.βε Jun 30 '15 at 20:48
  • @b.enoit.be It is all regexp syntax)) what exactly do you need ? –  Jun 30 '15 at 20:58
  • Me, nothing, your answer was in the low quality answer queue due to the fact that it is all but code and that the OP may not understand it at all ? And that further reader neither. – β.εηοιτ.βε Jun 30 '15 at 21:09