Replace string with incremented value

Posted by Andrei on Stack Overflow See other posts from Stack Overflow or by Andrei
Published on 2010-05-14T16:24:37Z Indexed on 2010/05/14 16:34 UTC
Read the original article Hit count: 213

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

© Stack Overflow or respective owner

Related posts about php

Related posts about string-manipulation