正在从字符串中检索数字字符


Retrieving numeric characters from a string

我有一个这样的字符串-

[ [ -2, 0.5 ],

我想检索数字字符,并将它们放入一个数组中,该数组最终看起来像这样:

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

做这件事最好的方法是什么?

编辑:

一个更全面的示例

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

我正在逐行地研究这个矩阵,我想把每一行的数字提取到一个数组中。

最容易使用的是正则表达式和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));

这里的好处是不需要不确定性或regex,并且它将正确地键入所有单独的元素(根据其值以int或float形式)。因此,上面的代码将输出:

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