dongpo5264 2012-08-01 14:56
浏览 18
已采纳

从字符串中检索数字字符

I have a string like this -

[ [ -2, 0.5 ],

I want to retrieve the numeric characters and put them into an array that will end up looking like this:

array(
  [0] => -2,
  [1] => 0.5
)

What is the best way of doing this?

Edit:

An more thorough example

[ [ -2, 0.5, 4, 8.6 ],
  [ 5,  0.5, 1, -6.2 ],
  [ -2, 3.5, 4, 8.6 ],
  [ -2, 0.5, -3, 8.6 ] ]

I am going through this matrix line by line and I want to extract the numbers into an array for each line.

  • 写回答

1条回答 默认 最新

  • dongping5230 2012-08-01 14:59
    关注

    The easiest thing to use is a regular expression and preg_match_all():

    preg_match_all( '/(-?\d+(?:\.\d+)?)/', $string, $matches);
    

    The resulting $matches[1] will contain the exact array you're searching for:

    array(2) {
      [0]=>
      string(2) "-2"
      [1]=>
      string(3) "0.5"
    }
    

    The regular expression is:

    (         - Match the following in capturing group 1
     -?       - An optional dash
     \d+      - One or more digits
     (?:      - Group the following (non-capturing group)
       \.\d+  - A decimal point and one or more digits
     )
     ?        - Make the decimal part optional
    )
    

    You can see it working in the demo.

    Edit: Since the OP updated the question, the representation of the matrix can be parsed easily with json_decode():

    $str = '[ [ -2, 0.5, 4, 8.6 ],
      [ 5,  0.5, 1, -6.2 ],
      [ -2, 3.5, 4, 8.6 ],
      [ -2, 0.5, -3, 8.6 ] ]';
    var_dump( json_decode( $str, true));
    

    The benefit here is that there's no uncertainty or regex required, and it will type all of the individual elements properly (as ints or floats depending on its value). So, the code above will output:

    Array
    (
        [0] => Array
            (
                [0] => -2
                [1] => 0.5
                [2] => 4
                [3] => 8.6
            )
    
        [1] => Array
            (
                [0] => 5
                [1] => 0.5
                [2] => 1
                [3] => -6.2
            )
    
        [2] => Array
            (
                [0] => -2
                [1] => 3.5
                [2] => 4
                [3] => 8.6
            )
    
        [3] => Array
            (
                [0] => -2
                [1] => 0.5
                [2] => -3
                [3] => 8.6
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?