php 我需要编辑此代码以使replase值

mzsu5hc0  于 2023-01-04  发布在  PHP
关注(0)|答案(1)|浏览(114)

我使用的URL = file_get_contents dom我得到一个数字作为一个值,有时只得到一个数字,有时得到一个数字+后者,如(12000 = 12K 20000 = 20K 150000= 150K 1000000 = 1M)
我需要编写一个简单的代码,将K替换为1000,将M替换为1000000,我已经将它们的值相加
原始代码:

$followers = $xpath->query("//span[@class='profile-followers']");
foreach($followers as $value) {
    $followed_by = $values[] = trim($value->textContent);
    $followed_by = str_replace('Followers', '', $followed_by);
    $followed_by = str_replace('', '', $followed_by);
}
im9ewurl

im9ewurl1#

怎么样

function numberParser(string|int|float $num): int|float
{
    $num = strtr(
        (string)$num,
        [
            ' ' => '', ',' => '',
            'K' => '000', 'M' => '000000', 'B' => '000000000',
        ]
    );
    $ret = filter_var($num, FILTER_VALIDATE_INT);
    if ($ret !== false) {
        return $ret;
    }
    $ret = filter_var($num, FILTER_VALIDATE_FLOAT);
    if ($ret !== false) {
        return $ret;
    }
    throw new Exception('Did not match any number format');
}

运行

$tests=[
    "1M",
    "100K",
    "123B"
];
foreach($tests as $test){
    var_dump([$test => numberParser($test)]);
}

给予

array(1) {
  ["1M"]=>
  int(1000000)
}
array(1) {
  ["100K"]=>
  int(100000)
}
array(1) {
  ["123B"]=>
  float(123000000000)
}

相关问题