简体   繁体   English

如何使用PHP有效地在不同位置替换字符串的一部分?

[英]How to replace part of a string at different positions efficiently using PHP?

I need to hide parts of a string like this 2345***47563****3432. 我需要隐藏这样的字符串部分2345 *** 47563 **** 3432。 I used PHP substr_replace as shown below which works but I am thinking if there is a better way of doing it instead of using nested substr_replace like I did. 我使用如下所示的PHP substr_replace可以正常工作,但是我在想是否有比使用嵌套的substr_replace更好的方法呢?

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

You can try this: 您可以尝试以下方法:

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

But I am not sure that this one is the easiest to read. 但是我不确定这是最容易阅读的。
And also, as you mentioned this one have another performance: 而且,正如您提到的那样,它还有另一种性能:

$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);

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM