2012-06-07 114 views
0

串看到这个代码:插入变量插入随机位置

<?php 

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

?> 

我如何可以插入$b$a随机位置?

+3

定义“休闲姿势”。你的意思是一个随机的位置? –

+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

编辑:倒过来。我读“插入到B,

+0

它的工作!你好! –

+0

@AldoHolm我向后读取OP,原始代码会将$ a插入到$ b中。修复了代码,使$ b变为$ a。 –

0

你应该把{$ B}上的{$ a}的,这样就可以把它插入到{$ B} .. 顶部如:

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

变量定义的顺序究竟与什么有关?只要这两个变量是由您使用它们的时间来定义的,顺序无关紧要。 –

+0

Tnks但这不是随机的位置 –

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

我想你可以通过治疗$一个作为字符串与$ 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 
0

演员$ a到字符串,然后用strlen得到$ a的长度,用rand和$ a的长度作为最大值,得到$ a中的一个随机位置,然后用substr_replace在$ a中插入$ b您刚刚随机分配的位置。