【问题标题】:How to replace part of a string at different positions efficiently using PHP?如何使用PHP有效地替换不同位置的部分字符串?
【发布时间】:2017-07-25 02:20:24
【问题描述】:

我需要隐藏部分字符串,例如 2345***47563****3432。我使用了如下所示的 PHP substr_replace,它有效,但我在想是否有更好的方法来代替像我那样使用嵌套的 substr_replace。

$mtn = 2348764756783432;
substr_replace(substr_replace($mtn, '***', 3,3 ), '***', 9, 3)
The result is 234***475***3432. 

【问题讨论】:

  • 改进了标题和语言,使其更清晰
  • @JorisMeys 完成。猜猜现在更清楚了。谢谢

标签: php replace


【解决方案1】:

你可以试试这个:

preg_replace('/(\d{3})(\d){3}/', '$1***', $mtn);

但我不确定这个是最容易阅读的。
而且,正如你提到的,这个还有另一种表现:

$mtn = 2348764756783432;

$time = microtime(true);
$result = substr_replace(substr_replace($mtn, '***', 3,3 ), '***', 9, 3);
printf('Result: %s, Spent time: %f %s', $result, microtime(true) - $time, PHP_EOL);

$time = microtime(true);
$result = preg_replace('/(\d{3})(\d){3}/', '$1***', $mtn);
printf('Result: %s, Spent time: %f %s', $result, microtime(true) - $time, PHP_EOL);

输出:

Result: 234***475***3432, Spent time: 0.000009 
Result: 234***475***3432, Spent time: 0.000092

【讨论】:

  • 感谢@Vladimir,将尝试一下,但在网上某处看到 substr 比 preg_replace 快
  • @CharlesOkaformbah 是的,这是真的!但这是另一种选择,可能不是最好的,而是另一种选择!)
猜你喜欢
  • 2011-06-28
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 2021-09-23
相关资源
最近更新 更多