lizaaard
lizaaard

Reputation: 33

PHP regex preg_match_all: Capturing text between multiple square brackets

I need to capture some string arrays.. and i've been trying but i can't :$

i've this in my code:

<?php
$feed = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";
preg_match_all("/\[(.*?)\]/",$feed,$matches);
print_r($matches);

and is returning:

Array
(
    [0] => Array
        (
            [0] => [['2013/04/03',8.300]
            [1] => ['2013/04/04',8.320]
            [2] => ['2013/04/05',8.400]
        )

    [1] => Array
        (
            [0] => ['2013/04/03',8.300
            [1] => '2013/04/04',8.320
            [2] => '2013/04/05',8.400
        )

)

how can i make with preg_match_all or preg_split.. or whatever method is needed to return one array of elements like the $matches[1][1] or $matches[1][2]??

i mean the format of each element should be:

'2013/04/05',8.400

hope to be clear :)

and thanks in advance!!

Upvotes: 3

Views: 1266

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You can try this:

<?php
$feed = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";
preg_match_all('~\[\K[^][]+~', $feed, $matches);
print_r($matches);

Upvotes: 1

Devtrix.net
Devtrix.net

Reputation: 763

If it would happen to be not a valid json, you could do simple manipulations with strings.

$arr = explode("],[", trim($str, " []"));

Output would be an array of with elements similar to this: "'2013/04/03',8.300" , "'2013/04/04',8.320"

This will work times faster than approach using RegExp methods.

Upvotes: 0

pp19dd
pp19dd

Reputation: 3633

This text appears to be in fairly normalized format, ala JSON. It's entirely possible to avoid reg matching and parse this with json_decode, albeit some minor transformations have to be made.

// original input
$text = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";

// standard transformation to correct ' and / characters
$text = str_replace( array('/', "'"), array('\/', '"'), $text );

// let native PHP take care of understanding the data
$data = json_decode( $text );

This gives you the array of arrays, containing your dates and values. print_r( $data ); gives:

Array (
    [0] => Array (
        [0] => 2013/04/03
        [1] => 8.3
    )
    [1] => Array (
        [0] => 2013/04/04
        [1] => 8.32
    )
    [2] => Array (
        [0] => 2013/04/05
        [1] => 8.4
    )
)

The transformations are replacing / to \/ and ' to " to make the string JSON-compliant. Or something to that effect.

Upvotes: 1

Related Questions