PHP - 从css中提取图像路径

时间:2011-04-16 18:09:05

标签: php regex

我有一个这样的样式表:

.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
}

我想获取具有无重复属性的图像路径。期待结果为fowllow:

array('../img/pen.png', '../img/delete.png')

3 个答案:

答案 0 :(得分:2)

此测试代码将执行此操作:

$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 :(得分:1)

我会逐行读取文件。

<?php

$image=array();
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$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);
  }
}

}

答案 2 :(得分:0)

如果你只是寻找背景(他们遵循这个选项顺序(网址,重复,休息)):

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
)