正则表达式替换前4位后的数字

时间:2011-04-29 08:21:10

标签: php javascript regex

我正在尝试编写一个正则表达式,用前4位数字替换*的所有数字。

例如

var number = 123456789  

应将其替换为1234*****

4 个答案:

答案 0 :(得分:5)

在Javascript中:

var maskedNumber = String(number).substr(0,4) + Array(String(number).length - 3).join('*');

在PHP中:

$maskedNumber = str_pad(substr($number, 0, 4), strlen($number), "*");

答案 1 :(得分:3)

在PHP中:

function replaceDigit_callback($matches) {
    return $matches[1] . str_repeat('*', strlen($matches[2]));
}
$text = '1234567890';
echo $text, "\n";
$text = preg_replace_callback('#(\d{4})(\d+)#', 'replaceDigit_callback', $text);
echo $text, "\n";

输出:

1234567890
1234******

在JS中:

var number = 1234567890;
var output = number.toString().replace(/(\d{4})(\d*)/, function (str, p1, p2) { return p1 + p2.replace(/./g, '*') });

答案 2 :(得分:0)

你可以设置你的PHP编码..我为你提供逻辑......

using System;
using System.Text.RegularExpressions;

class RegexSubstitution
{
   public static void Main()
   {
      string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
      Regex testRegex1 = new Regex( @"\d" );

      Console.WriteLine( "Original string: " + testString1 );
      Console.WriteLine( "Replace first 3 digits by \"digit\": " + testRegex1.Replace( testString1, "digit", 3 ) );
   }
}

答案 3 :(得分:0)

没有正则表达式:

var number = '123456789';
var output = '';

output = number.substr(0,4);
for ( var i = 0; i < number.length - 4; ++i )
{
    output += '*';
}

输入number必须是字符串!

转换

var number = 1234567890;

到字符串看起来就像:

var number = 1234567890 + '';

var number = parseString(1234567890);