doumanju2533 2018-08-20 19:46
浏览 33
已采纳

带有int或float to number的PHP字符串

If I have two strings in an array:

$x = array("int(100)", "float(2.1)");

is there a simple way of reading each value as the number stored inside as a number?

The reason is I am looking at a function (not mine) that sometimes receives an int and sometimes a float. I cannot control the data it receives.

function convertAlpha($AlphaValue) { 
    return((127/100)*(100-$AlphaValue));
}

It causes an error in php

PHP Notice: A non well formed numeric value encountered

which I want to get rid of.

I could strip the string down and see what it is and do an intval/floatval but wondered if there was a neat way.

UPDATE:

Playing about a bit I have this:

function convertAlpha($AlphaValue) {

$x = explode("(", $AlphaValue);
$y = explode(")", $x[1]);

if ($x[0] == "int") {
    $z = intval($y[0]);
}

if ($x[0] == "float") {
    $z = floatval($y[0]);
}

return((127/100)*(100-$z)); }

This which works but it just messy.

  • 写回答

4条回答 默认 最新

  • dqpfkzu360216 2018-08-20 20:08
    关注
    <?php
    
    $x = array("int(100)", "float(2.1)");
    
    $result = [];
    
    foreach($x as $each_value){
        $matches = [];
        if(preg_match('/^([a-z]+)(\((\d+(\.\d+)?)\))$/',$each_value,$matches)){
            switch($matches[1]){
              case "int": $result[] = intval($matches[3]); break;
              case "float": $result[] = floatval($matches[3]);
            }
        }
    }
    
    print_r($result);
    

    OUTPUT

    Array
    (
        [0] => 100
        [1] => 2.1
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动