Search code examples
phpphp4

PHP replace string with alternating srings


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


Solution

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