Hirantha
Hirantha

Reputation: 33

Convert a JavaScript regexp function to a php

I have a function using js replace and having hard time converting it to php

The JS code (both does the same thing see js fiddle links)

function number_to_code(s) {

  // converting the value to something like 50000.00 to look like currency
  // next replace it with the codes as bellow.  
s = parseFloat(s).toFixed(2).replace(/\d/g, m => ({
    '0': 'I',
    '1': 'N',
    '2': 'E',
    '3': 'S',
    '4': 'T',
    '5': 'O',
    '6': 'M',
    '7': 'A',
    '8': 'L',
    '9': 'D'
  })[m]);

  // grouping it with , 
  s = s
    .replace(/([A-Z])(\1+)/g, (_, g1, g2) => {
      return g1 + g2.replace(/./g, "Z")
    })
    .replace(/\B(?=(\w{3})+(?!\w))/g, ",")

  return s;
}

they convert the currency value to a text code.

I think php preg_replace is the function to use. I can't understand the

(_, g1, g2) => {
      return g1 + g2.replace(/./g, "Z")

part

Upvotes: 1

Views: 71

Answers (2)

Hirantha
Hirantha

Reputation: 33

Ah with Help from the @WiktorStribiżew I managed to get the final output.

For anyone looking for a good tutorial on php preg_replace() https://stackoverflow.com/a/21631013/1814051

$string = "500000120034000567080900";  //test string

$a = array("0"=>"I", "1"=>"N", "2"=>"E","3"=>"S","4"=>"T","5"=>"O","6"=>"M","7"=>"O","8"=>"L","9"=>"D");
$pattern = '/(\d)/';
$pattern2 = '/II+/';

// the function call
$result = preg_replace_callback($pattern,
function($matches) {
  //  echo ($matches[1]." ");
    global $a;  
 return  $a[$matches[1]];
},$string);

$result2 = preg_replace_callback($pattern2,  
// the callback function
function($matches) {
  return  substr_replace(str_replace("I","Z",$matches[0]),"I",0,1);
  
 //return  $a[$matches[0]];
},$result);


echo "<br/>".$result;
echo "<br/>".$result2;

OIIIIINEIISTIIIOMOILIDII    <= intermediate step to help understand.
OIZZZZNEIZSTIZZOMOILIDIZ    <= this is the output I was looking for

Upvotes: 1

You can use the php function that does the same thing preg_replace_callback the only difference is that the preg_replace_callback function only has one param which is an array of the matches.

For instance:

$string = "1 1";
preg_replace_callback('/(\d) (\d)', function($matches) {
    // The first position of the $matches is the whole string
    // The second position is the first group and so on...
    // And then you can return whatever you want, using or not the groups from the matches
}, $string);

Upvotes: 1

Related Questions