Jim_CS
Jim_CS

Reputation: 4172

Retrieving numeric characters from a string

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.

Upvotes: 0

Views: 119

Answers (1)

nickb
nickb

Reputation: 59699

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
        )

)

Upvotes: 5

Related Questions