请参阅此代码:
<?php
$a = rand(1, 10000000000);
$b = "abcdefghi";
?>
如何将$b
插入$a
的随机位置?
假设"随意"意味着随机:
<?php
$a = rand(1, 10000000000);
$b = "abcdefghi";
//get a random position in a
$randPos = rand(0,strlen($a));
//insert $b in $a
$c = substr($a, 0, $randPos).$b.substr($a, $randPos);
var_dump($c);
?>
上面的代码工作: http://codepad.org/VCNBAYt1
编辑:有变量向后。我读到"将 a 插入 b,
我想你可以通过将$a视为字符串并将其与$b连接起来:
$a = rand(1, 1000000);
$b= "abcd";
$pos = rand(0, strlen($a));
$a = substr($a, 0, $pos).$b.substr($a, $pos, strlen($a)-$pos);
结果如下:
a=525019
pos=4
a=5250abcd19
a=128715
pos=5
a=12871abcd5
你应该把 {$b} 放在 {$a} 的上面,这样你就可以把它插入到 {$b}。例如:
<?php
$b = "abcdefghi";
$a = rand(1, 10000000000);
$a .= $b;
echo $a;
?>
像
这样
:<?php
$position = GetRandomPosition(); // you will have to implement this function
if($position >= strlen($a) - 1) {
$a .= $b;
} else {
$str = str_split($a, $position);
$a = $str[0] . $b . implode(array_diff($str, array($str[0])));
}
?>
将$a转换为字符串,然后使用 strlen 获取$a的长度。 使用 rand,长度为 $a 为最大值,以获得$a内的随机位置。然后使用substr_replace将$b插入您刚刚随机化的位置$a中。