1

I am trying to build a regex that captures successfully the following bolded text:

background-image: url( https://domain/adress/with/other/stuff?alsoaquerystring=whynot );

Expected output is:

https://domain/adress/with/other/stuff?alsoaquerystring=whynot

And this is what I have tried so far, but I can't manage to say "capture everything that's inside here, no matter what characters it has got".

/background-image: url\((?P<image>)+\)/;

It needs to be compatible with PHP preg_replace().

GiamPy
  • 3,543
  • 3
  • 30
  • 51
  • 1
    Use `background-image: url\((?P[^)]+)\)`. What is the expected output? – Wiktor Stribiżew Mar 29 '17 at 14:59
  • Added the expected output. – GiamPy Mar 29 '17 at 15:00
  • I do not think you need a named capturing group, just use a numbered one (in PHP `preg_replace`, you can't use named backreferences in the *string* replacement pattern). See http://ideone.com/lHqXFZ. – Wiktor Stribiżew Mar 29 '17 at 15:07
  • I know, but is there a reason for which I should NOT use a named capture group? I mean, is it heavier on a performance point-of-view, or it is just useless but nothing bad actually happens? And I have already used named capturing groups with `preg_match()`! – GiamPy Mar 29 '17 at 15:09
  • See http://stackoverflow.com/questions/5255149/named-backreferences-with-preg-replace. You may still keep them, but in the replacement pattern, use corresponding numbered backreferences. – Wiktor Stribiżew Mar 29 '17 at 15:13
  • Maybe it does work only with `preg_match()` but not with `preg_replace()`? – GiamPy Mar 29 '17 at 15:14
  • 1
    They work, but you cannot reference them by name from the string replacement pattern. – Wiktor Stribiżew Mar 29 '17 at 15:14

1 Answers1

0

You can use:

background-image: url\((.*?)\);

By using ( ) you are creating a capture group in regex.

See https://regex101.com/r/VNsTPU/1/ as an example. It's a very basic example, you can improve to strip out white space between parentheses or just trim after you are done.

See this answer about using capture groups with PHP, if you are unfamiliar.

Update: If you are trying to do it with preg_replace this is how you would do it:

$regex = = 'background-image: url\((.*?)\);';
$var = 'background-image: url( https://domain/adress/with/other/stuff?alsoaquerystring=whynot )';
preg_replace($regex,'$1',$var);
Community
  • 1
  • 1
Halfwarr
  • 7,853
  • 6
  • 33
  • 51