我有类似"X los(2) - XYZ tres"
的字符串
我如何找到所有大写字母和单词并用随机数字替换它们?
从第一个字符串我应该得到"2 los(2) - 6 tres"
或"9 los(2) - 5 tres"
我的意思是,一个大写单词应该变成一个个个位数。
我就是这么做的。
使用正则表达式查找大写字符组,并将其替换为0
和9
之间的随机数字(十进制中的所有个位数)。
$str = preg_replace_callback('/[A-Z]+/', function() {
return rand(0, 9);
}, $str);
CodePad。
您可以使用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]
中发现匹配
要兼容unicode,请使用unicode属性p{Lu}
,它表示任何语言中的任何大写字母:
$str = preg_replace_callback('/p{Lu}+/', function() {
return rand(0, 9);
}, $str);
试试这个
preg_replace_callback('/([A-Z]+)/', function(){
return mt_rand(0, 9);
}, "X los(2) - XYZ tres");