Hello,

I have the following string:

// [ { "id": "694653" ,"t" : "Faaf" ,"e" : "652" ,"l" : "279.43" ,"l_cur" : "279.43" } ]

I am trying to using preg_split and regex to capture all characters contained within double quotes and store them into an array. When finished I want an array that looks like this.

Array [0] => id [1] => 694653 [2] => t [3] => Faaf [4] => e [5] => 654 [6] => l [7] => 279.43 [8] => l_cur [9] => 279.43

For the life of me I am unable to conjure up the correct regex to do this. Was curious if anyone could help.

Thanks.

Joe

    Here is my crack at it:

    $str = '// [ { "id": "694653" ,"t" : "Faaf" ,"e" : "652" ,"l" : "279.43" ,"l_cur" : "279.43" } ]';
    preg_match_all('#: "([^"]+)" ,"([^"]+)"#', $str, $matches);
    echo '<pre>'.print_r($matches[1], true).print_r($matches[2], true);
    

    Ouput:

    Array
    (
        [0] => 694653
        [1] => Faaf
        [2] => 652
        [3] => 279.43
    )
    Array
    (
        [0] => t
        [1] => e
        [2] => l
        [3] => l_cur
    )
    

    So basically, you can always pair up $matches[1] with $matches[2].
    So by printing $matches[1][0] with $matches[2][0] would give you: 694653 t by example.

      You know, sometimes I get things wrong and add un-necessary complications.. try this instead:

      $str = '// [ { "id": "694653" ,"t" : "Faaf" ,"e" : "652" ,"l" : "279.43" ,"l_cur" : "279.43" } ]'; 
      preg_match_all('#"([^"]+)"#', $str, $matches); 
      echo '<pre>'.print_r($matches[1], true);
      

      Output:

      Array
      (
          [0] => id
          [1] => 694653
          [2] => t
          [3] => Faaf
          [4] => e
          [5] => 652
          [6] => l
          [7] => 279.43
          [8] => l_cur
          [9] => 279.43
      )
      

        You my friend are a regex rockstar. Never thought about using preg_match_all but it makes sense. Thanks for taking the time to help me out, I appreciate it.

        -Joe

          Write a Reply...