0

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.

4

1 回答 1

5

最容易使用的是正则表达式和preg_match_all()

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

结果$matches[1]将包含您正在搜索的确切数组:

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

正则表达式是:

(         - 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
)

您可以在演示中看到它的工作原理。

编辑:由于OP更新了问题,矩阵的表示可以很容易地解析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));

这里的好处是不需要不确定性或正则表达式,它将正确键入所有单个元素(根据其值作为整数或浮点数)。因此,上面的代码将输出

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
        )

)
于 2012-08-01T14:59:49.453 回答