开发者

Why doesn't this PHP regular expression extract the url from the css value?

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);
开发者_StackOverflow社区print_r($matches);

and it gives me :

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
        )

)


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';


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.


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)[\'\"]?)\)/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜