0

I am stuck in a problem that I have a string which has a complete description as well as a json containing some Ids. How can I take the Json out the String and perform any event on it..

My data looks like following

The description of xxxxxxxxxxxxxxxxxxxxxxxxxx
[{"id":"613"},{"id":"614"},{"id":"615"}]

Is there any way that I can have the Complete Description and also have the IDs so that I can decode them and use where I want?

Thank you in advance for the support

Nabeel Arshad
  • 45
  • 1
  • 7
  • If the description is not always just one line or there's any other proper limitation (such as not containing a `{` making that character the first JSON char all the time) you'll probably have to use a brute-force solution. See http://stackoverflow.com/a/10574546/298479 for an example (written in JavaScript but you can port it to PHP) – ThiefMaster Nov 13 '12 at 08:23
  • Are they always separated by a newline? – Asad Saeeduddin Nov 13 '12 at 08:24

2 Answers2

1

try this

$string = 'The description of xxxxxxxxxxxxxxxxxxxxxxxxxx    [{"id":"613"},{"id":"614"},{"id":"615"}] asdasd';

if(false !== preg_match('/\[(.*)\]/', $string, $matches)) {
    for($n = 1; $n < count($matches); $n++) {
        $json_result = json_decode('['.$matches[$n].']', true);
        if(null === $json_result) {
            //cannot parse json
        }
        print_r($json_result);
    }
}
silly
  • 7,789
  • 2
  • 24
  • 37
0

This will find the first LINE which has JSON code if your json is in new line !!!

$string = 'The description of xxxxxxxxxxxxxxxxxxxxxxxxxx
[{"id":"613"},{"id":"614"},{"id":"615"}]';
$strings = explode("\n",$string);

foreach($strings as $str){
    $json = json_decode($str,TRUE); //TRUE for array responde
    if(!empty($json)){
       break;
    }
}

var_dump($json);
Svetoslav
  • 4,686
  • 2
  • 28
  • 43