Regex: search urls in CSS background image

Here is my regex code:

preg_match_all('/background[-image]*:[\s]*url\(["|\']+(.*)["|\']+\)/', $css, $matches, PREG_SET_ORDER); 

He is looking for CSS that looks like this:

 background:url('../blah.jpg'); 

My problem I am facing is the CSS that I scratch looks like this:

 background:transparent url('../blah.jpg'); background:transparent no-repeat url('../blah.jpg'); 

I'm not an expert when it comes to regex, so I wonder how I can say that it skips something after the colon and before the URL.

+6
source share
3 answers

Ths should catch all the images if I didn't miss anything.

 preg_match_all('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$str,$matches); $images = $matches['image']; print_r($images); 
+14
source
 preg_match_all('/background(-image)??\s*?:.*?url\(["|\']??(.+)["|\']??\)/', $css, $matches, PREG_SET_ORDER); 

I replaced :[\s]* with :.*? that the trick should do - means that it will match any character, the previous regular expression matches only spaces after :

+1
source

Try the following:

 preg_match_all('/background[-image]*:.*[\s]*url\(["|\']+(.*)["|\']+\)/', $css, $matches, PREG_SET_ORDER); 
0
source

Source: https://habr.com/ru/post/911770/


All Articles