在随机位置将变量插入字符串

时间:2012-06-07 16:29:26

标签: php

请参阅此代码:

<?php

$a = rand(1, 10000000000);
$b = "abcdefghi";

?>

如何将$b插入$a的随机位置?

5 个答案:

答案 0 :(得分:4)

假设“随意”意味着随机:

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

编辑:让vars倒退了。我读过“插入一个b,

答案 1 :(得分:1)

我猜你可以将$ 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

答案 2 :(得分:0)

您应该将{$ b}放在{$ a}之上,以便将其插入{$ b}。 例如:

<?php
   $b = "abcdefghi";
   $a = rand(1, 10000000000);
   $a .= $b;
   echo $a;
?>

答案 3 :(得分:0)

像这样:

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

答案 4 :(得分:0)

将$ a转换为字符串,然后使用strlen获取$ a的长度。使用rand,以$ a的长度作为最大值,以获得$ a内的随机位置。然后使用substr_replace在您刚刚随机化的位置将$ b插入$ a。