【问题标题】:Replace digits in a number with other random digits用其他随机数字替换数字中的数字
【发布时间】:2017-03-06 13:43:53
【问题描述】:

问题:

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

示例:

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

其中 xxxx 是 4 位或 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, -?);
}

【问题讨论】:

  • $num = substr_replace($num, random_int(1000, 9999), 5, 4); 怎么样?
  • 如果你总是想替换第5、6、7和8位,不用担心长度。您可以阅读并学习如何将数字转换为字符串,这样可以更轻松地替换您想要的数字,而不是尝试做一些数学运算。

标签: php string random replace


【解决方案1】:

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

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

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

function mynumber(&$x) {

【讨论】:

  • 谢谢。因此,正确且 good 的语法可能类似于:function mynumber($x) { $replacement = var_dump(random_int(1000, 9999)); $x = substr_replace($x, $replacement, 5, 4); return $x; }
猜你喜欢
  • 2012-06-24
  • 2020-08-14
  • 2017-05-20
  • 2018-08-23
  • 2021-05-18
  • 2021-11-02
  • 2017-12-17
  • 1970-01-01
  • 2022-07-25
相关资源
最近更新 更多