0

i have a regex challenge i can't solve on my own, i have a json stringified file that hold lots of entries so instead of decoding it and looping over all items i want just use a preg_replace to delete a specific item with specific id.

so my json look like this:

    [  
          {  
             "id":"440",
             "type":"prospect",
             "fullname":"elizabeth cogelizabeth",
             "phone":"01768413081",
             "..." : ""
          },
          {  
             "id":"436",
             "type":"prospect",
             "fullname":"mandy cogmandy",
             "phone":"01697349008",
             "..." : ""
          }
]

what i know is the id part so i can do something like this

preg_replace('/{\"id\"\:\"440\".*?\"},/', '', $jsonBlob);

unfortunately my regex don't keep in count the last item that doesn't end with comma , but with a bracket ]

any help is really appreciated. thanks in advance.

7
  • Not sure what you mean, your example doesn't have a ] that should cause ", to fail. I think {\s*"id":"440", or {\s*"id":"\d+", is easier to read. Commented May 9, 2016 at 16:13
  • 4
    i don't think it is a rather good idea using preg_replace here looping through json_decode array is far better Commented May 9, 2016 at 16:14
  • 2
    In the future I will name my child {bobby} just to throw off lazy code like this. Commented May 9, 2016 at 16:15
  • 1
    the issue here is also how fail safe are both ways not only how fast, best of all is if you have both of course, fast and fail safe @JulieRokk Commented May 9, 2016 at 16:32
  • 1
    Some People rather like to challenge themselves only for the purpose of growth & advancement. @Julie Rokk stated clearly, QUOTE: ...so instead of decoding it and looping over all items i want just use a preg_replace.... She already knew she could decode & loop & do it easily but still WITHOUT CHALLENGES, WHO EVER GROWS? & no one would register with SO if it were not for discovering new, better (& even strange) ways of doing things; because the sum total of 1 man's knowledge may just be a single byte vis-à-vis another man's Plus: 1 selfless act of help goes a long way!* Commented May 10, 2016 at 11:33

3 Answers 3

1

Loop through JSON example using the id, in your case you don't need to use unset().

$json = '[  
          {  
             "id":"440",
             "type":"prospect",
             "fullname":"elizabeth cogelizabeth",
             "phone":"01768413081",
             "..." : ""
          },
          {  
             "id":"436",
             "type":"prospect",
             "fullname":"mandy cogmandy",
             "phone":"01697349008",
             "..." : ""
          }
]';
$arr = json_decode($json,true);
foreach($arr as $key => $value) {
if($value['id']==436) { 
unset($arr[$key]); // delete this entry from results
// $value = your_new_json_object {id,type,..}
}
}
print_r($arr);

Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

({\s*\"id\":\"440\"[^}]*)((\s*},)|(\s*}\s*])|(\s*}\s*}\s*])|(\s*}\s*},)) regex101.com/r/xX5nD8/1 , regex101.com/r/xX5nD8/2 i am not a regex expert but this does the work :) Test it further if you wish by altering the internal of your json. It should fetch by id even if element is last in json (] instead of ,) , or try having a last sub-element like "...":{} instead of "...":""
1

Would you mind to try this Function and see if it does the trick for you?

    <?php


        // PASS IN THE ID YOU WANNA FILTER-OUT AS $id,
        // 2ND PARAMETER IS THE JSON STRING
        // 3RD PARAMETER IS THE REPLACEMENT STRING: IN YOUR CASE EMPTY: ""
        function removeJsonBlock($id, $jsonSTR, $replacement="YEAH!!! IT WORKS!!!"){
            $jsonSTR      = trim($jsonSTR);
            $filteredJson = preg_replace('#(\{\s*)([\'\"]id[\'\"]\:)(\s?[\'\"])' . trim($id) . '([\'\"])([\w,\.;\"\'\-\?\:\s_\n\r]+)(\},?)#si', $replacement, $jsonSTR);
            return $filteredJson;
        }

        // THE JSON STRING IN QUESTION - REGARDLESS OF WHETHER DYNAMIC OR NOT.
        $jsonSTR =<<<JSS
        [
              {
                 "id":"440",
                 "type":"prospect",
                 "fullname":"elizabeth cogelizabeth",
                 "phone":"01768413081",
                 "..." : ""
              },
              {
                 "id":"436",
                 "type":"prospect",
                 "fullname":"mandy cogmandy",
                 "phone":"01697349008",
                 "..." : ""
              },
              // ADD ANOTHER NODE WITH THE SAME ID OF 440 FOR EXAMPLE...
              {
                 "id":"440",
                 "type":"prospect",
                 "fullname":"elizabeth cogelizabeth",
                 "phone":"01768413081",
                 "..." : ""
              },
        ]
JSS;

        // TEST THE SIMULATION... IT SHOULD REMOVE EVERY ENTRY WITH ID: 440
        var_dump(removeJsonBlock(440, $jsonSTR));


        //

I hope it helps in a little bit.... ;-)

1 Comment

tnx, unfortunately this does not work if i select the last item in the json string resulting in an invalid array
0

You can use this regex:

{\s*"id":"440"[^}]*}

As a string that's:

$re = "/{\\s*\"id\":\"440\"[^}]*}/im";

This assumes that id is the first value in the JSON array, but it will account for whitespace. It uses [^}]* to grab everything up to the }.

Since you're looking to delete the item, the regex can be changed to look for commas before or after the match. I have also included a way for the item to match if it is the only thing in the array:

,\s*{\s*"id":"440"[^}]*}|{\s*"id":"440"[^}]*}\s*,|{\s*"id":"440"[^}]*}

It's easier to read with x spacing enabled:

,\s*{\s*"id":"440"[^}]*}    |
    {\s*"id":"440"[^}]*}\s*,|
    {\s*"id":"440"[^}]*}

2 Comments

nice one but this will not remove the comma after or before the item resulting in an invalid array
@JulieRokk I've added a version that matches commas.

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.