Take the 2-minute tour ×

Here's my regex code:

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

It looks for CSS that looks like this:


My problem I'm having is some CSS I scrape looks like this:

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

I'm no expert when it comes to regex, so I'm wondering how I can tell it to skip anything after the colon and before URL.

share|improve this question
add comment

3 Answers

up vote 11 down vote accepted

Ths should catch all the images unless I skipped anything.

$images = $matches['image'];
share|improve this answer
BTW, <image> adds the matched string to $matches['image']? I didn't know that! Good one!! –  mrsafraz Mar 27 '12 at 16:26
Yep. $matches normally catches all the parenthesized values and the whole match but once you know where exactly you want to get regardless of where it is in your regex you can use labels. It's much more practical. –  inhan Mar 27 '12 at 16:45
Thanks for the explanation :) –  mrsafraz Mar 28 '12 at 14:43
You're welcome :) –  inhan Mar 28 '12 at 20:05
This is matching non-URLs for me. Specifically, gradients; had to add url before the parenthesis. –  Anthony Topper Feb 19 at 0:20
add comment
preg_match_all('/background(-image)??\s*?:.*?url\(["|\']??(.+)["|\']??\)/', $css, $matches, PREG_SET_ORDER);

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

share|improve this answer
[-image]* means Zero or more of the characters [-aegim]. (-image)? would be better. –  Xeoncross Mar 27 '12 at 16:13
you're right! I didn't notice that part –  mrsafraz Mar 27 '12 at 16:17
add comment

Try this:

preg_match_all('/background[-image]*:.*[\s]*url\(["|\']+(.*)["|\']+\)/', $css, $matches, PREG_SET_ORDER);
share|improve this answer
How do you check if it has no double or single quote? Can't quit seem how to pass "nothing" lol as an options –  Banning Oct 31 '12 at 16:33
add comment

Your Answer


