如何用星号替换字符串的一部分?

时间:2011-04-25 07:56:11

标签: php regex

使用preg_replace(), 我想替换像这样的字符串......

aaabbbccc => aaa******
cccdddfff => ccc******
234456789 => 234******
12wcced => 12w*****
123cde => 123***

如何使用正则表达式preg_replace()执行此操作?

2 个答案:

答案 0 :(得分:7)

echo substr($string, 0, 3) . str_repeat('*', max(0, strlen($string) - 3));

不完全preg_replace,但是......

答案 1 :(得分:2)

假设> = PHP 5.3

$str = 'abcdefg';

$str = preg_replace_callback('/^(.{3})(.*)$/', function($matches) {
   return $matches[1] . str_repeat('*', strlen($matches[2]));
}, $str);

echo $str; // abc****

CodePad

但是,使用Deceze's answer可以更好地实现像您的示例这样的字符串。

相关问题