views:

48

answers:

2

Hello,

I'm trying to write a CSS parser to automatically dispatch URLs in background images to different subdomains in order to parallelize downloads.

Basically, I want to replace things like

url(/assets/some-background-image.png)

with

url(http://assets[increment].domain.com/assets/some-background-image.png)

I'm using this inside a class that I eventually want to evolve into doing various CSS parsing tasks.

Here are the relevant parts of the class :

private function parallelizeDownloads(){
    static $counter = 1;
    $newURL = "url(http://assets".$counter.".domain.com";

The counter needs to be reset when it reaches 4 in order to limit to 4 subdomains.

    if ($counter == 4) {
        $counter = 1;
    }
    $counter ++;
    return $newURL;
}

public function replaceURLs() {

This is mostly nonsense, but I know the code I'm looking for looks somewhat like this. Note : $this->css contains the CSS string.

    preg_match("/url/i",$this->css,$match);
    foreach($match as $URL) {
        $newURL = self::parallelizeDownloads();
        $this->css = str_replace($match, $newURL,$this->css);
    }
}
A: 

set $counter as a property of the class, and reference it as $this->counter, or self::$counter if you set it as a static property

You're calling self::parallelizeDownloads() in your public replaceURLs() method, so parallelizeDownloads() should really be defined as static

Mark Baker
Thanks for the advice. I've modified the code but I'm still not getting any incremented values. I think there's a problem with the replaceURLs() method...
Andrei
You also probably want to useif ($counter == 4) { $counter = 0; } $counter ++; otherwise you reset the counter to 1, then immediately increment it to 2.Your loop in replaceURLs() isn't doing much though, because you keep overriding $this->css
Mark Baker
Thanks ! Looking at it it seems obvious now, that's why I wasn't seeing any increments in the replaced URLs. Still, how would I go about getting this to work ? Is preg_match the right tool for this ?
Andrei
A: 

Ok, I finally got it working using preg_replace_callback. Here's the code :

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);
}
Andrei