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.

2
  • Are the numbers always going to be between square braces with commas between them? Commented Aug 1, 2012 at 14:59
  • At present I think so. They are representing matrices of variable size. I'll edit the post to show an example. Commented Aug 1, 2012 at 15:05

1 Answer 1

5

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
        )

)
Sign up to request clarification or add additional context in comments.

2 Comments

I love the way you explained the regular expression. Awesome job!
That's cool that json_decode works. This is purely co-incidental that this matrix format is encoded in the same way. The matrix data structures here are from a program that's almost a decade older than PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.