Change Php 1 to 1000

I want to make a variable when converting 1k or 1.5k to 1000 or 1500

I tried preg_replace, but I do not work for me because it adds “000” to the number, so I would get 1000 and 1,5000

Thank you

+3
source share
5 answers
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;

The outputs are "1000" and "1500". You can see for yourself here .

+2
source

You should try to remove k and multiply the result by 1000.

$digit = "1,5k";
$digit = str_replace(k, "", $digit);
$digit *= 1000;
+2
source

if, ",", , 00, 000. "k", kk ' ...

0

, . $ = $input//1k 1.5k    , k 00    k 000

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

All Articles