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

如何使用PHP高效地替换位于不同位置的字符串的一部分?,php,replace,Php,Replace,我需要隐藏像2345***47563****3432这样的字符串部分。我使用了PHP substr_替换,如下所示,它可以工作,但我想是否有更好的方法来代替像我那样使用嵌套的substr_替换 $mtn = 2348764756783432; substr_replace(substr_replace($mtn, '***', 3,3 ), '***', 9, 3) The result is 234***475***3432. 您可以尝试以下方法: preg_replace('/(\d{3

我需要隐藏像2345***47563****3432这样的字符串部分。我使用了PHP substr_替换,如下所示,它可以工作,但我想是否有更好的方法来代替像我那样使用嵌套的substr_替换

$mtn = 2348764756783432;
substr_replace(substr_replace($mtn, '***', 3,3 ), '***', 9, 3)
The result is 234***475***3432. 
您可以尝试以下方法:

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

改进了标题和语言,使其更加clear@JorisMeys完成。我想现在更清楚了。thanksthanks@Vladimir将尝试一下,但在网上的某个地方读到substr比preg快_replace@CharlesOkaformbah是的,这是真的!但这是另一种选择,可能不是最好的,而是另一种选择!)