脑洞打开的方法
$str='111111112111212111121211112112121111111';
$arr=explode('2',$str);
$new='';
foreach($arr as $k=>$v){
$new.=($k==2 ? '8': ($k==0 ? '' : '2')).$v;
}
echo $str.'<br>';//111111112111212111121211112112121111111
echo $new.'<br>';//111111112111812111121211112112121111111
$str='111111112111212111121211112112121111111';
$arr=explode('2',$str);
$new='';
foreach($arr as $k=>$v){
$new.=($k==2 ? '8': ($k==0 ? '' : '2')).$v;
}
echo $str.'<br>';//111111112111212111121211112112121111111
echo $new.'<br>';//111111112111812111121211112112121111111
$check='2';
$count= strlen($str);
$rand=rand(0,20);
$first=strpos($str,'2');
$last=strrpos($str,'2');
for($i=0;$i<$count;$i++){
if($number!=$first&&$number!=$last){
if($str[$rand]=='2'){
if($check==$str[$i]){
$str=substr_replace($str,'8',$number,1);
}
}
}
}
不知道你是不是要这样子的效果
1.首先遍歷字符串,找到要替換的字符集合,記錄下標。
2.把第一個和最後一個下標的排除。
3.在剩下的下標中隨機,得到要替換的下標
4.替換。
$str = '111111112111212111121211112112121111111';
$search = '2';
$replace = '8';echo random_replace($str, $search, $replace);function random_replace($str, $search, $replace){ $arr = str_split($str);
$tmp = array(); foreach($arr as $k=>$v){
if($v==$search){
array_push($tmp, $k);
}
} if(count($tmp)>2){
$t = mt_rand(1,count($tmp)-2);
$arr[$tmp[$t]] = $replace;
} return implode('',$arr);
}
$str='111111112111212111121211112112121111111';
$arr=explode('2',$str);
$new='';
$random_position = rand(2, count($arr)-2);
foreach($arr as $k=>$v){
$new.=($k==$random_position ? '8': ($k==0 ? '' : '2')).$v;
}
echo $str.'<br>';//111111112111212111121211112112121111111
echo $new.'<br>';//111111112111812111121211112112121111111
$n = rand(2, substr_count($s, '2') - 1);
echo $s . '<br>';
for($i=0; $i<strlen($s); $i++) {
if($s{$i} == 2 && --$n == 0) {
$s{$i} = '8';
break;
}
}
echo $s;
$s = '111111112111212111121211112112121111111';
$max = substr_count($s, '2');
if ($max < 3) {
exit();
}
$num = rand(2, $max - 1);
$s = preg_replace("/8/", "2", preg_replace("/2/", "8", $s, $num), $num - 1);
echo $s;