0

I want to extract the url from the background css property "url('/img/hw (11).jpg') no-repeat". I tried:

$re     = '/url\(([\'\"]?.*\.[png|jpg|jpeg|gif][\'\"]?)\)/i';
$text   = "url('/img/hw (11).jpg')";
preg_match_all($re, $text, $matches);
print_r($matches);

and it gives me :

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
        )

)
2
  • What are you trying to extract from that string? The image URL? Commented Oct 6, 2011 at 16:21
  • Not checking for the extension, but as file extensions do not have to say anything in URLs: sscanf($text, 'url(%*[\'"]%[^\'"]', $url); Commented Oct 6, 2011 at 16:27

3 Answers 3

3

Here is the correct regex. The ".*" in the middle of your regex is too greedy. Also, try replacing the square brackets with paranthesis. Also note that since you are using single quotes around the string that you do not need to escape the double quotes.

$re     = '/url\(([\'"]?.[^\'"]*\.(png|jpg|jpeg|gif)[\'"]?)\)/i';
Sign up to request clarification or add additional context in comments.

Comments

3

Try:

/url\(([\'\"]?.*\.(png|jpg|jpeg|gif)[\'\"]?)\)/i

Instead. The square brackets do a character-by-character comparison rather than the or comparison you're looking for.

Comments

1

I think the probably lies in this part [png|jpg|jpeg|gif]. It's supposed to match only single characters.
You should do this instead :

/url\([\'\"]?(.*\.(jpg|png|jpeg|gif)[\'\"]?)\)/

Comments

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.