将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;
}
- https://jsfiddle.net/uevntfhb/
- https://jsfiddle.net/j9cdrq73/5/
它们将货币值转换为文本代码。
我认为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
相关文章