views:

71

answers:

4

I am using PHP to match the following data type :

[["1200","135"],["127","13"]]

I want to extract all the numbers into a seperate array of arrays like this :

array(array(1200,135),array(127,13));

I am using preg_match to capture the elements but so far i am not even able to match them against a rule. I will gladly appreciate if someone can help me correct my rule or even provide a solution as to how to accomplish this.

My regex rule is : / ^[ ([" (\d+) "," (\d+) "])*(,)* ]$ /

I've kept it unescaped to make it more readable on this forum. However it doesn't work. Please help

+3  A: 

A few mistakes in your regexp are: using start and end anchors (^ and $) and not escaping the square brackets.

But do use json_decode(), that's what it's for.

Vinko Vrsalovic
+10  A: 

Try

var_dump( json_decode('[["1200","135"],["127","13"]]') );

gives:

array(2) {
  [0]=> array(2) {
    [0]=> string(4) "1200"
    [1]=> string(3) "135"
  }
  [1]=> array(2) {
    [0]=> string(3) "127"
    [1]=> string(2) "13"
  }
}

See PHP Manual:

Gordon
+1 best solution
alex
+1. JSON is not a regular language.
Stuart Branham
A: 

It seems you are processing JSON, so use json decode, like this :

php > print_r(json_decode('[["1200","135"],["127","13"]]'));
Array
(
    [0] => Array
        (
            [0] => 1200
            [1] => 135
        )

    [1] => Array
        (
            [0] => 127
            [1] => 13
        )

)
greg0ire
+1  A: 

Quite easy:

  $proper = '[["1200","135"],["127","13"]]';
  $nuked = '[["1200",,"135"],[["127","13"]]';
  $pattern = '/[["[0-9]*","[0-9]*"],["[0-9]*?","[0-9]*"]]/s';
  echo "proper: ". preg_match($pattern, $proper);
  echo "<br>";
  echo "nuked: ". preg_match($pattern, $nuked);

Outputs:

proper: 1
nuked: 0

Pretty much it has to look exactly as you have given it except the data between the " can change. I hope this is what you wanted?

laconix
According to that regex, this string is well formed: `",""],[",""]]`
Alan Moore
It appears it does, I didn't really test it that much as I much prefer to avoid regex as it seems like a really inelegant solution to any problem.
laconix