
PHP如何给文章随机位置添加固定代码?
要求如下例如以下这段文字,从开头算起,在30到100个字符这个区间的随机位置插入代码1,然后从代码1后面的第一个字符算起的20到50字符这个区间的随机位置插入代码2。接着...
要求如下
例如以下这段文字,从开头算起,在30到100个字符这个区间的随机位置插入代码1,然后从代码1后面的第一个字符算起的20到50字符这个区间的随机位置插入代码2。接着从代码2结束的地方算起,重复前面这两步,直到文本结束。
In the wild, the Giant Panda is a terrestrial animal and primarily spends its life roaming and feeding in the bamboo forests of the Qinling Mountains and in the hilly Sichuan Province. Though generally alone, each adult has a defined territory and females are not tolerant of other females in their range. Pandas communicate through vocalization and scent marking such as clawing trees or spraying urine. The Giant Panda is able to climb and take shelter in hollow trees or rock crevices but does not establish permanent dens. For this reason, pandas do not hibernate, which is similar to other subtropical mammals, and will instead move to elevations with warmer temperatures.
Pandas rely primarily on spatial memory rather than visual memory.
谢谢了 展开
例如以下这段文字,从开头算起,在30到100个字符这个区间的随机位置插入代码1,然后从代码1后面的第一个字符算起的20到50字符这个区间的随机位置插入代码2。接着从代码2结束的地方算起,重复前面这两步,直到文本结束。
In the wild, the Giant Panda is a terrestrial animal and primarily spends its life roaming and feeding in the bamboo forests of the Qinling Mountains and in the hilly Sichuan Province. Though generally alone, each adult has a defined territory and females are not tolerant of other females in their range. Pandas communicate through vocalization and scent marking such as clawing trees or spraying urine. The Giant Panda is able to climb and take shelter in hollow trees or rock crevices but does not establish permanent dens. For this reason, pandas do not hibernate, which is similar to other subtropical mammals, and will instead move to elevations with warmer temperatures.
Pandas rely primarily on spatial memory rather than visual memory.
谢谢了 展开
1个回答
展开全部
假设你的文字变量名为$str,需要插入的代码变量名为$ad[1], $ad[2], .....
$textlength = strlen($str);
$curpos = ($textlength >= 100) ? rand(30, 100) : ($textlength > 30 ? rand(30, $textlength) :$textlength);
$curadid = 1;
while($curpos < $textlength){
$str = substr($str, 0, $curpos).$ad[$curadid].substr($str, $curpos, $textlength);
$curpos += rand(20, 50) + strlen($ad[$curadid]);
if($ad[$curadid + 1]) $curadid += 1;
}
这其中你有个没有说的地方,如果文本不够30个字符怎么办?不可能插入30 - 100之间吧。所以我加入个判断,不够30时加入末尾。
另外,文章可能更长,比如10000个字符,却只有2段代码,我这个写法会自动插入代码2,如果已经没有代码3了。
$textlength = strlen($str);
$curpos = ($textlength >= 100) ? rand(30, 100) : ($textlength > 30 ? rand(30, $textlength) :$textlength);
$curadid = 1;
while($curpos < $textlength){
$str = substr($str, 0, $curpos).$ad[$curadid].substr($str, $curpos, $textlength);
$curpos += rand(20, 50) + strlen($ad[$curadid]);
if($ad[$curadid + 1]) $curadid += 1;
}
这其中你有个没有说的地方,如果文本不够30个字符怎么办?不可能插入30 - 100之间吧。所以我加入个判断,不够30时加入末尾。
另外,文章可能更长,比如10000个字符,却只有2段代码,我这个写法会自动插入代码2,如果已经没有代码3了。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询