Str_replace不适用于十六进制

时间:2017-09-10 04:20:13

标签: php

为什么不使用此代码。我需要在大文本文件中将hex转换为int。 我不知道如何解决它。

//array with hex +9999 length
$number1 = ["90.5E1","11.46E2" "81.60E1","0x216","0xffff","8.05E2","33.30E1","0x21C"];
//file with hex +9999 length
$file = '90.5E1 0x216 8.05E2 8.05E2';

foreach ($number1 as $value) {
    $int = (int)$value;
    $file = str_replace($value,$int,$file);
}

return $file;

2 个答案:

答案 0 :(得分:0)

你的数组中有一个解析错误,你错过了一个逗号!

//array with hex +9999 length
$number1 = ["90.5E1","11.46E2", "81.60E1","0x216","0xffff","8.05E2","33.30E1","0x21C"];
//file with hex +9999 length
$file = '90.5E1 0x216 8.05E2 8.05E2';

foreach ($number1 as $value) {
    $int = (int)$value;
    $file = str_replace($value,$int,$file);
}

echo $file;

返回:905 0 805 805

答案 1 :(得分:0)

您可以使用"0xFF"intval("0xFF", 0)之类的字符串转换为十六进制。 0使其检测到0x前缀并自动从十六进制转换。

//array with hex +9999 length
$number1 = ["90.5E1","11.46E2","81.60E1","0x216","0xffff","8.05E2","33.30E1","0x21C"];
//file with hex +9999 length
$file = '90.5E1 0x216 8.05E2 8.05E2';

foreach ($number1 as $value) {
    if (substr($value, 0, 2) == '0x')
        $int = intval($value, 0);
    else
        $int = (int)$value;
    $file = str_replace($value,$int,$file);
}

echo $file;

输出:905 534 805 805

修改

如果要在不使用$number1的情况下替换值,可以按空格拆分文件并替换每个值:

$file = '90.5E1 0x216 8.05E2 8.05E2';

$file = preg_replace_callback('/([^ ]+)/', function ($matches) {
  $value = $matches[0];
  if (substr($value, 0, 2) == '0x')
    return intval($value, 0);
  else
    return (int)$value;
}, $file);

echo $file;

输出:905 534 805 805