对任何数字添加千位分隔符,即使它包含特殊字符


Add Thousand separator to any number even if it contains special characters

我有一个挪威语价格格式的网站,因此产品价格显示为1000,-

这是一个基于Magento的站点,版本为ce-1.9.2.1。

现在我想添加千个分隔符(很可能是空格,但可以是任何字符)到该价格,通过使用number_format函数或regex保持其格式,以保持完整性最好的(如1 000,-, 1 000 000,-等)。

谁有什么建议?

preg_replace中使用查找,你可以这样做:

$str = preg_replace('/'..*$(*SKIP)(*F)|(?<='d)(?=(?:'d{3})+(?!'d))/', ' ', $str);

'..*$(*SKIP)(*F)将忽略/跳过DOT之后的部分。

RegEx演示

根据我在google上5分钟的研究,挪威克朗的正式货币格式是#.###,##

此格式与您建议的格式之间的唯一区别是,Krone分隔符是""而不是",00",并且特殊值",-"øre被替换为"CC_12"。

基于上述观察,我将简单地运行以下代码,并在正式定义中给出一个正确格式化的值:
// expects "1.234,00" returns "1 234,-"
//     "1.234.567,00" ==> "1 234 567,-"
//              5,50  ==>          5,50
function kroneDisplayFormat($formalFormat) {
    $intermediate = str_replace(".", " "); // replace . separator with ' ' (space)
    if( endsWith( $intermediate, ",00")) {
       // special display case ",00" ==> ",-"
       $final = str_replace(",00", ",-");
    } else {
       $final = $intermediate
    }
    return $final
}