PHP - 从CSS中提取图像路径

4

我有一个像这样的样式表:

.d2 {
    position:absolute;
    background:url(../img/delete.png) no-repeat 0px 1px;
    color:#0066CC;
}
.reply {
    position:absolute;
    background:url(../img/pen.png) no-repeat 0px 1px;
    top:5px
}
#about {
    position:absolute;
    background:url(../img/abc.png);
    top:5px
}

我希望获取没有no-repeat属性的图片路径。期望的结果如下:

array('../img/pen.png', '../img/delete.png')
3个回答

3
这段经过测试的代码可以实现此功能:
$imgs = array();
$re = '/url\(\s*[\'"]?(\S*\.(?:jpe?g|gif|png))[\'"]?\s*\)[^;}]*?no-repeat/i';
if (preg_match_all($re, $text, $matches)) {
    $imgs = $matches[1];
}

1
我会逐行读取文件。
<?php

$image = [];
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    if (strpos($line, 'no-repeat') {
        if (strpos($line, '.png')) {
            $urlpos = strpos($line, 'url');
            $rightone = strpos($line, '(', $urlpos);
            $leftone = strpos($line, ')', $rightone);

            array_push($images, substr($line, $rightone, $leftone - $rightone));
        }
    }
}

0
如果你只是想获取背景(并且它们按照这些选项的顺序排列(URL、重复、其余)):
preg_match_all('~background:\s*url\(['"]?([^)]+)['"]?\)\s+no-repeat[^;]*;~i', $css, $reg);

print_r($reg[1]);

输出:

Array
(
    [0] => ../img/delete.png
    [1] => ../img/pen.png
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接