2012-03-17 129 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); 
相关问题