用其他随机数字替换数字中的数字


Replace digits in a number with other random digits

问题:

  • 我正试图写一个函数来替换一个数字中的四位数字
  • 数字语法为XX.XXXXXXXX(但长度可能有所不同,但至少为8位数字(
  • 我想更改的数字总是第5、第6、第7和第8位(标记为Z->XX.XXXZZXXXX(
  • 替换Z的数字必须是随机的(或每个Z中有4个随机数字(

示例:

x=12.3456789 --> function --> 12.34xxxx9

其中xxxx是一个随机数,有4个数字或四个不同的数字。

文档:

  • 替换
  • 生成随机数

我尝试过的:

注意:我从编码开始。。。这里的超级新秀。

function mynumber($x) {
//ok, it's not elegant but here i'm trying to get a number of 4 digits instead of digit by digit
$replacement = var_dump(random_int(1111, 9999));
//I've read about string replace but as the lenght may vary, i don't know how to delimitate the digits i want to change
$x = str_replace($x, $replacement, -?);
}

使用substr_replace()作为str_replace()将替换其他匹配的数字,而不仅仅是第5位到第8位:

$x = substr_replace($x, $replacement, 5, 4);

此外,您需要在函数中使用return $x;。或者要修改传递的变量,需要通过引用传递:

function mynumber(&$x) {