Youss
Youss

Reputation: 4212

Regex not working properly in PHP

I have this data:

{"names":["George","Eric","Alice"]}

And I want to use preg_match_all to filter out the words in between quotation like this:

$s = $data;

if (preg_match_all('/"([^:]*)"/', $s, $matches)) {
        echo join("\n", $matches[1]);
}

But this is outputting names George","Eric","Alice I tried many things but I cant figure it out.

Upvotes: 2

Views: 67

Answers (4)

user2169391
user2169391

Reputation:

Since your data is json formatted you should really treat is as json and not process it with regex which is to be used for strings. Try this:

$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data['names'] as $item) echo "$item\n";

Or without the hard coded "names":

$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data as $arr) foreach($arr as $item) echo "$item\n";

Upvotes: 1

falsetru
falsetru

Reputation: 369094

* matches greedy (as much as possible). Use non-greey version: *?

if (preg_match_all('/"([^:]*?)"/', $s, $matches)) {
    echo join("\n", $matches[1]);
}

output:

names
George
Eric
Alice

UPDATE

json_decode is more appropriate for this kind of work. Try following:

foreach (json_decode($s, true) as $key => $value) {
    echo $key . "\n";
    echo join("\n", $value);
}

Upvotes: 3

Arrok
Arrok

Reputation: 116

try this

$strContent = '{"names":["George","Eric","Alice"]}';
$strRegex = '%\"(.+?)\"%s';
if (preg_match_all($strRegex, $strContent, $arrMatches))
{
    var_dump($arrMatches[1]);
}

Upvotes: 1

anubhava
anubhava

Reputation: 785196

This is actually JSON string use json_decode to parse it rather than using regex on this:

print_r(json_decode('{"names":["George","Eric","Alice"]}', true));

OUTPUT:

Array
(
    [names] => Array
        (
            [0] => George
            [1] => Eric
            [2] => Alice
        )

)

Upvotes: 2

Related Questions