开发者

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 th开发者_StackOverflowe 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...


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜