0

I have a text something like this:

    $sText =    
    "www.domain.com
     www.domain.com
     www.domain.com
     www.domain.com
     www.domain.com
     ...";

Now I want to spread the domains to subdomains (e.g. 3 sub-domains), so the result should look like this:

$aSubs = array("www.sub1.domain.com", "www.sub2.domain.com", "www.sub3.domain.com"); 
$sResult =
"www.sub1.domain.com
www.sub2.domain.com
www.sub3.domain.com
www.sub1.domain.com
www.sub2.domain.com
..."

Thanks for help...

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
Ilyssis
  • 4,849
  • 7
  • 24
  • 30

3 Answers3

1

In your replace callback, do something similar to this:

static $i = 0;
'www.' . ($i++ % 3 + 1) . '.domain.com';

I'm leaving writing the regex to you (as you didn't give any details.)

PS: The static keyword in a function refers to a variable that is maintained between several function calls.

NikiC
  • 100,734
  • 37
  • 191
  • 225
1

If you have PHP 5.3:

preg_replace_callback($sText, "#www\.domain\.com#", function() {
    static $index = 0;
    $subdomains = array(
        "www.sub1.domain.com",
        "www.sub2.domain.com",
        "www.sub3.domain.com",
        "www.sub1.domain.com",
        "www.sub2.domain.com",
    );
    return $subdomains[$index++ % count($subdomains)];
});
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • @Ilysis: Even 5.3 ^^ But you can do the same thing by putting the `function()` code in a separate function and passing the name of the function in quotes to `preg_replace_callack`. – NikiC Jan 27 '11 at 15:28
0

This could work:

<?php
$count = 0;
$subdomains = array("www.sub1.domain.com", "www.sub2.domain.com", "www.sub3.domain.com");

$text = <<<XXX
www.domain.com
www.domain.com
www.domain.com
www.domain.com
www.domain.com
XXX;


function createSub($matches)
{
    global $subdomains,$count;
    $index = $count++ % count($subdomains);
    return $subdomains[$index];
}
echo preg_replace_callback(
            "#(www)(\..+)#m",
            "createSub",
            $text);     
SERPRO
  • 10,015
  • 8
  • 46
  • 63