2012-03-17 187 views

回答

3

這是我該怎麼做的。

使用正則表達式來查找大寫字母組,並用09(十進制系統中的所有單個數字)之間的隨機數字替換它們。

$str = preg_replace_callback('/[A-Z]+/', function() { 
    return rand(0, 9); 
}, $str); 

CodePad

+1

或者一次,合法和安全地使用'e'修飾符:'preg_replace('/ [AZ] +/e',「rand(0,9)」,$ str);' – DaveRandom 2012-03-17 09:35:41

+0

@DaveRandom是的,如果沒有捕獲組插入到代碼中,我猜'e'標記是安全的:) – alex 2012-03-17 09:37:24

1

您可以使用preg_replace_callback查找大寫字母,並用隨機數替換它們。

$text = "X los(2) - XYZ tres"; 

// the callback function 
function replace_with_random($matches) 
{ 
    return rand(0,9); 
} 

//perform the replacement 
$text= preg_replace_callback(
      "/[A-Z]+/", 
      "replace_with_random", 
      $text); 

回調可以檢查匹配文本不是一些隨機執行更復雜的替代品 - 你會發現在$matches[0]

0

那場比賽試試這個

preg_replace_callback('/([A-Z]+)/', function(){ 
    return mt_rand(0, 9); 
}, "X los(2) - XYZ tres"); 
+0

您不需要回調,這很簡單。 – Rezigned 2012-03-17 09:35:14

+2

這將取代與相同的隨機數,不像OP給出的例子。 – alex 2012-03-17 09:35:35

+0

哦,你說得對。 – Rezigned 2012-03-17 09:36:57

1

要兼容Unicode,使用unicode \p{Lu}這意味着任何語言的任何大寫字母:

$str = preg_replace_callback('/\p{Lu}+/', function() { 
    return rand(0, 9); 
}, $str); 
相關問題