tags:

views:

55

answers:

2

I want to replace a user define format like...

ABC-####-09

to

ABC-0023-09

How many leading zero should be decide over how many '#' sign in format, and the length of default value to replace (23 in this case).

Is there any regular expression pattern to do this?

Thanks...

+2  A: 

How about this?

$num = 23;
$format = 'ABC-####-09';
print preg_replace('/(#+)/e', 'str_pad($num, strlen("$1"), 0, STR_PAD_LEFT)', $format);
Paolo Bergantino
+1  A: 

This should work in Javascript:

function user_str_replace {

  var match = user_input.match(/#+/);
  var length = match.length;

  var str = your_number.toString();
  var newStr = "";
  for (var i = 0; i < length - str.length; i ++) {
    newStr = "0" + newStr;
  }
  newStr = newStr + str;

  return (newStr);
}
Crimson
Nice! But it should be -- for(i=0; i<length-str.length; i++)...Thanks... :-)
Ei Maung
made the edit :)
Crimson