将JavaScript regexp函数转换为php [英] Convert a JavaScript regexp function to a php

查看:34
本文介绍了将JavaScript regexp函数转换为php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用js替换的函数,但很难将其转换为php

JS代码(两者做同样的事情,参见js小提琴链接)

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;
}

它们将货币值转换为文本代码。

我认为php preg_place是要使用的函数。 我听不懂

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

部件

推荐答案

ah在@wiktorStribiż的帮助下,我终于获得了最终输出。

任何正在寻找关于php preg_place()的好教程的人 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

这篇关于将JavaScript regexp函数转换为php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆