2012-08-01 115 views
0

检索数字字符我有一个​​这样的字符串 -从字符串

[ [ -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 ] ] 

我要通过线这个矩阵线,我想的数字解压缩到每行的阵列。

+0

数字总是会在两个方括号之间用逗号隔开吗? – Palladium 2012-08-01 14:59:31

+0

目前我这么认为。它们表示可变大小的矩阵。我将编辑帖子以显示示例。 – 2012-08-01 15:05:16

回答

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 
) 

你可以看到它在the demo

编辑:由于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)); 

这样做的好处是,有没有不确定性或正则表达式必需的,它会输入所有的单个元素都是正确的(作为整数或浮点数取决于它的值)。所以,上面的代码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 
     ) 

) 
+0

我喜欢你解释正则表达式的方式。好工作! – 2012-08-01 15:08:25

+0

+1,用于智能使用'json_decode'。 – Palladium 2012-08-01 15:14:41

+0

伟大的回答欢呼声。 – 2012-08-01 15:39:11