从字符串中检索数字字符 [英] Retrieving numeric characters from a string

查看:55
本文介绍了从字符串中检索数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串 -

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?

更详细的例子

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

推荐答案

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

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

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

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

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

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
)

您可以在演示中看到它的运行情况.

You can see it working in the demo.

由于 OP 更新了问题,因此可以使用 轻松解析矩阵的表示json_decode():

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
        )

)

这篇关于从字符串中检索数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆