我的文字是这样的:
$sText =
"www.domain.com
www.domain.com
www.domain.com
www.domain.com
www.domain.com
...";
现在我想将域扩展到子域(例如3个子域),因此结果应如下所示:
$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
..."
感谢您的帮助...
答案 0 :(得分:1)
在替换回调中,执行与此类似的操作:
static $i = 0;
'www.' . ($i++ % 3 + 1) . '.domain.com';
我要把正则表达式写给你(因为你没有提供任何细节。)
PS:函数中的static
关键字是指在多个函数调用之间维护的变量。
答案 1 :(得分:1)
如果你有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)];
});
答案 2 :(得分:0)
这可行:
<?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);