Php change 1k to 1000
i want to make a variable when transforms 1k or 1,5k in开发者_开发知识库to 1000 or 1500
i tried preg_replace but i doesn't work for me becasue it adds "000" to number so i'd get 1000 and 1,5000
thank you
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;
Outputs "1000" and "1500". You can see for yourself here.
You should try to remove the k and multiply the result with 1000.
$digit = "1,5k";
$digit = str_replace(k, "", $digit);
$digit *= 1000;
Crete a function and in that function do an if statement that checks for ',' and if it found it you can add 00 and not 000. Also in that function you could check for not only 'k', but also 'kk' for millions and such...
You could make it dependent on the comma, e.g. in pseudo code $i=$input //1k or 1.5k if contains comma remove all commas, replace k with 00 else replace k with 000
$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;
}
精彩评论