将Php中的1k更改为1000

3
我希望在将1k或1.5k转换为1000或1500时创建一个变量。
我尝试使用preg_replace,但它对我无效,因为它会将“000”添加到数字中,所以我得到的是1000和1,5000。
谢谢。

你在 preg_replace 中尝试了哪个具体的正则表达式? - user142162
1
为什么不去掉 'k' 并乘以 *1000? - Damien Pirsy
1
一旦您将k转换为其数字等价物,就可以使用number_format()添加漂亮的格式。 - Marc B
我想把它乘以1000,但我不知道怎么做:D - Miso
请问您想要创建一个“变量”还是“函数()”? - Sujit Agarwal
5个回答

2
function expand_k($str) {
    // If the str does not end with k, return it unchanged.
    if ($str[strlen($str) - 1] !== "k") {
        return $str;
    }

    // Remove the k.
    $no_k = str_replace("k", "", $str);
    $dotted = str_replace("," , ".", $no_k);

    return $dotted * 1000;
}    

$a = "1k";
$b = "1,5k";

$a_expanded = expand_k($a);
$b_expanded = expand_k($b);

echo $a_expanded;
echo $b_expanded;

输出结果为"1000"和"1500"。 您可以在此处自行查看。


2
你应该尝试去掉 k 并将结果乘以 1000。
$digit = "1,5k";
$digit = str_replace(k, "", $digit);
$digit *= 1000;

0
$s = "This is a 1,5k String and 1k ";

echo replaceThousands($s);

function replaceThousands($s)
{
    $regex = "/(\d?,?\d)k/";
    $m = preg_match_all($regex, $s, $matches);

    foreach($matches[1] as $i => $match)
    {
        $new = str_replace(",", ".", $match);
        $new = 1000*$new;
        $s = preg_replace("/" .$match."k/", $new, $s);
    }

    return $s;
}

0
创建一个函数,在该函数中执行if语句,检查“,”,如果找到了它,您可以添加00而不是000。此外,在该函数中,您还可以检查不仅“k”,而且“kk”以表示百万等...

0
你可以让它依赖于逗号,例如在伪代码中: $i=$input //1k or 1.5k 如果包含逗号 删除所有逗号,将k替换为00 否则 将k替换为000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接