我的目标是得到这样的东西:150.000,54
或48.876,05
,这意味着我的逗号是十进制开头。
到目前为止,这是我的代码:
<?php
//cut numbers after comma if there are any, after 2 digits
$matchPattern = '/[0-9]+(?:',[0-9]{2}){0,2}/';
//remove everything except numbers, commas and dots
$repl1 = preg_replace("/[^a-zA-Z0-9,.]/", "", $input);
//let there be a 0 before comma to have values like 0,75
$repl2 = preg_replace("/^[0]{1}$/", "",$repl1);
//now i need you here to help me for the expression putting dots after each 3 numbers, until the comma:
$repl3 = preg_replace("/regexphere$/", ".", $repl2);
preg_match($matchPattern, $repl3, $matches);
echo($matches[0]);
?>
我知道preg_replace三次是愚蠢的,但我不擅长写正则表达式。如果你有更好的想法,不要只是分享,还要解释。我知道一些类型:
http://regexone.com/lesson/0
提前谢谢。
--------更新--------
因此,我需要处理类似0000,45
的0,45
输入和类似010101,84
的1,84
输入
当这一切结束后,我就完了。
$input = Input::get('userinput');
$repl1 = preg_replace("/[^0-9,.]/", "", $input);
$repl2 = preg_replace("/^0/", "",$repl1);
$repl3 = str_replace(".","",$repl2);
preg_match('/[0-9]+(?:',[0-9]{2}){0,2}/', $repl3, $matches);
$repl4 = preg_replace('/('d)(?=('d{3})+(?!'d))/', '$1.', $matches[0]);
return repl4;
----更新----
到目前为止,我得到的是:https://ideone.com/5qmslB
我只需要去掉逗号前和数字前的零。
我不确定这是最好的方法,但我希望它能有所帮助。
这是我在伪造的$input
:中使用的更新代码
<?php
$input = "textmdwrhfejhg../,2222233333,34erw.re.ty";
//cut numbers after comma if there are any, after 2 digits
$matchPattern = '/[0-9]+(?:',[0-9]{2}){0,2}/';
//remove everything except numbers, commas and dots
$repl1 = trim(preg_replace("/[^0-9,.]/", "", $input), ".,");
echo "$repl1" . "'n";
//let there be a 0 before comma to have values like 0,75, remove the 0
$repl2 = preg_replace("/^0/", "",$repl1);
echo "$repl2" . "'n";
//The expression putting dots after each 3 numbers, until the comma:
$repl3 = preg_replace('/('d)(?=(?:'d{3})+(?!'d))/', '$1.', $repl2);
echo "$repl3" . "'n";
表达式将点放在每3个数字后面是
('d)(?=(?:'d{3})+(?!'d))
在这里,你可以看到它是如何工作的。在普通人中,
('d)
-我们将在替换模式中使用的捕获组,匹配一个(?=(?:'d{3})+(?!'d))
-后面跟着一组3位数字。外部(?=...)
是一种检查但不消耗字符的前瞻性结构,(?:'d{3})+
是一个非捕获组(无需将匹配的文本保存在内存中),它与3位数字精确匹配(由于限定量词{3}
)1次或更多次(由于+
量词),并且CCD_ 14是检查最后匹配的3位组之后的下一个字符不是数字的否定前瞻
如果十进制分隔符后面有超过3位数字,这将不起作用。使用regex,我只能想出一种方法来支持(?<!,)('d)(?=(?:'d{3})+(?!'d))
的小数后4位数字。不确定在PHP中是否有一种通用的方法没有可变宽度的后向查看(就像这里一样,我们也需要可变宽度的前向查看)。因此,您可以考虑用逗号分隔$repl2
值,并只将第一部分传递给regex。然后,组合。类似这样的东西:
$spl = split(',', $repl2); // $repl2 is 1234,123456
$repl3 = preg_replace('/('d)(?=(?:'d{3})+(?!'d))/', '$1.', $spl[0]);
$repl3 .= "," . $spl[1]; // "1.234" + "," + "123456"
echo "$repl3" . "'n"; // 1.234,123456
更新:
我想出的最后一个代码:
$input = "textmdwrhfejhg../0005456,2222233333,34erw.re.ty";
//Here's mine :
$repl1 = trim(preg_replace("/[^0-9,.]/", "", $input), '.,');
//following line just removes one zero, i want it to remove all chars like
//Input : 000549,569 Output : 549,569
echo "$repl1'n";
$repl2 = preg_replace("/^0+(?!,)/", "",$repl1);
$repl3 = str_replace(".","",$repl2);
preg_match('/[0-9]+(?:',[0-9]{2}){0,2}/', $repl3, $matches);
$repl4 = preg_replace('/('d)(?=('d{3})+(?!'d))/', '$1.', $matches[0]);
echo $repl4;