eval.in

Paste #105218

PHP — PHP 5.4.6, pasted 5 years ago (json)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

/*
 * @link: http://stackoverflow.com/a/21995025/1438393
 */
 
$text = <<<TEXT
This is a funny text about stuff,
look at this product {"action":"product","options":{"foo":"bar"}}.
More Text is to come and another JSON string
{"action":"review","options":{...}}
TEXT;

$pattern = '/\{(?:[^{}]|(?R))*\}/';

preg_match_all($pattern, $text, $matches);
print_r($matches[0]);

function isValidJSON($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

$valid_json_arr = array_filter($matches[0], 'isValidJSON');
print_r($valid_json_arr);

Program Output

Array
(
    [0] => {"action":"product","options":{"foo":"bar"}}
    [1] => {"action":"review","options":{...}}
)
Array
(
    [0] => {"action":"product","options":{"foo":"bar"}}
)

OK (0.008 sec real, 0.008 sec wall, 13 MB, 74 syscalls)

Fork