2017-03-15 148 views
1

我想用另一個隨機字符替換字符串ABC123EFG中的每個數字。
我的想法是用$str中的所有數字生成一個隨機字符串,並將每個數字替換爲$array[count_of_the_digit],有沒有辦法在沒有for循環的情況下執行此操作,例如使用正則表達式?用隨機字符替換字符串中的每個數字

$count = preg_match_all('/[0-9]/', $str); 
$randString = substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", $count)), 0, $count); 
$randString = str_split($randString); 
$str = preg_replace('/[0-9]+/', $randString[${n}], $str); // Kinda like this (obviously doesnt work) 
+0

我想不出任何你會得到一串沒有循環的隨機字符串。你爲什麼不想使用循環? (這是否只是我,還是有時似乎有人告訴新的程序員,循環是壞的?) – alanlittle

+0

它不是循環是壞的,它似乎可以用正則表達式或類似的東西乾淨地完成 – nn3112337

回答

2

你可以使用preg_replace_callback()

$str = 'ABC123EFG'; 

echo preg_replace_callback('/\d/', function(){ 
    return chr(mt_rand(97, 122)); 
}, $str); 

這將輸出類似:

ABCcbrEFG 

如果你想大寫值,你可以改變97122其對應的ASCII碼的6490

+1

我有同樣的準備粘貼:-( – AbraCadaver

+0

偉大的思想認爲一樣:-) – Xorifelse

+0

謝謝,正是我一直在尋找! – nn3112337

0

您可以使用preg_replace_callback調用返回值爲替換值的函數。下面是一個你想要的例子:

<?php 
function preg_replace_random_array($string, $pattern, $replace){ 
    //perform replacement 
    $string = preg_replace_callback($pattern, function($m) use ($replace){ 
      //return a random value from $replace 
      return $replace[array_rand($replace)]; 
     }, $string); 

    return $string; 
} 

$string = 'test123asdf'; 

//I pass in a pattern so this can be used for anything, not just numbers. 
$pattern = '/\d/'; 
//I pass in an array, not a string, so that the replacement doesn't have to 
//be a single character. It could be any string/number value including words. 
$replace = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'); 

var_dump(preg_replace_random_array($string, $pattern, $replace));