我正在尝试编写一个CSS解析器,以自动将背景图像中的URL分发到不同的子域,以便并行化下载。
基本上,我想替换像
这样的东西url(/assets/some-background-image.png)
与
url(http://assets[increment].domain.com/assets/some-background-image.png)
我在一个类中使用它,我最终想要进行各种CSS解析任务。
以下是该课程的相关部分:
private function parallelizeDownloads(){
static $counter = 1;
$newURL = "url(http://assets".$counter.".domain.com";
当计数器达到4时需要重置,以限制为4个子域。
if ($counter == 4) {
$counter = 1;
}
$counter ++;
return $newURL;
}
public function replaceURLs() {
这主要是废话,但我知道我正在寻找的代码看起来有点像这样。注意:$ this-> css包含CSS字符串。
preg_match("/url/i",$this->css,$match);
foreach($match as $URL) {
$newURL = self::parallelizeDownloads();
$this->css = str_replace($match, $newURL,$this->css);
}
}
答案 0 :(得分:0)
将$ counter设置为类的属性,如果将其设置为静态属性,则将其引用为$ this-> counter或self :: $ counter
您在公共replaceURLs()方法中调用self :: parallelizeDownloads(),因此parallelizeDownloads()应该真正定义为static
答案 1 :(得分:0)
好的,我终于使用preg_replace_callback了解它。这是代码:
private function parralelizeDownloads($matches) {
static $counter = 1;
$newURL = '';
foreach ($matches as $match) {
$newURL = "url(http://assets" . $counter . ".domain.com";
if ($counter == 4) {
$counter = 0;
}
$counter++;
}
return $newURL;
}
public function replaceURLs() {
$this->css = preg_replace_callback("/url\(/i", Array($this, "parralelizeDownloads"), $this->css);
}