Reputation: 4212
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
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
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
Reputation: 116
try this
$strContent = '{"names":["George","Eric","Alice"]}';
$strRegex = '%\"(.+?)\"%s';
if (preg_match_all($strRegex, $strContent, $arrMatches))
{
var_dump($arrMatches[1]);
}
Upvotes: 1
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