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

2
  • 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 stackoverflow.com/a/10574546/298479 for an example (written in JavaScript but you can port it to PHP) Commented Nov 13, 2012 at 8:23
  • Are they always separated by a newline? Commented Nov 13, 2012 at 8:24

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.