6

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:

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

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.

3 Answers 3

18

Ths should catch all the images unless I skipped anything.

preg_match_all('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$str,$matches);
$images = $matches['image'];
print_r($images);
Sign up to request clarification or add additional context in comments.

3 Comments

BTW, <image> adds the matched string to $matches['image']? I didn't know that! Good one!!
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.
This is matching non-URLs for me. Specifically, gradients; had to add url before the parenthesis.
1

Try this:

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

1 Comment

How do you check if it has no double or single quote? Can't quit seem how to pass "nothing" lol as an options
1
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 :

1 Comment

[-image]* means Zero or more of the characters [-aegim]. (-image)? would be better.

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.