我希望在将1k或1.5k转换为1000或1500时创建一个变量。
我尝试使用preg_replace,但它对我无效,因为它会将“000”添加到数字中,所以我得到的是1000和1,5000。
谢谢。
我尝试使用preg_replace,但它对我无效,因为它会将“000”添加到数字中,所以我得到的是1000和1,5000。
谢谢。
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"。 您可以在此处自行查看。
$digit = "1,5k";
$digit = str_replace(k, "", $digit);
$digit *= 1000;
$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;
}
preg_replace
中尝试了哪个具体的正则表达式? - user142162number_format()
添加漂亮的格式。 - Marc B