Search code examples
phpstringsubstr

Get substrings from that string format


I have the following data and I can have 3 different cases:

Case 1:

"afield1" : "something1", "credentials" : [] , "afield2" : "something2" 

Case 2:

"afield1" : "something1", "credentials" : [ ["root", "toor"] ] , "afield2" = "something2"

Case 3:

"afield1" : "something1", "credentials" : [ [ "admin", "support" ], [
"admin", "password" ], [ "admin", "123321" ] ] , "afield2" : "something2"

how can I get get the usernames and passwords?

Edit:

I found a silly way for the first case.. But the others are so compliated.. It can not be exploded neither on comma (,) or braket ([ ]) ... Help if something knows how to explode correct or get the values from that thing...


Solution

  • You can use a preg_match and preg_match_all functions like in this code

    $credentials = [];
    
    $text = '"afield1" = "something1", "credentials" : [ [ "admin", "support" ], ["admin", "pass]word" ], [ "admin", "123321" ] ] , "afield2" = "something2"';
    
    preg_match('/"credentials" : \[(.*?)\] ,/i', $text, $matches);
    preg_match_all('/\[[ ]?"(.*?)"[ ]?\]/i', $matches[1], $matches2);
    
    foreach ($matches2[1] as $match) {
        preg_match_all('/"(.*?)"/i', '"' . $match . '"', $matches3);
    
        $credential = ['login' => $matches3[1][0], 'password' => $matches3[1][1]];
        $credentials[] = $credential;
    }
    
    var_dump($credentials);
    

    On the ouptut you can see

    array(3) {
      [0]=>
      array(2) {
        ["login"]=>
        string(5) "admin"
        ["password"]=>
        string(7) "support"
      }
      [1]=>
      array(2) {
        ["login"]=>
        string(5) "admin"
        ["password"]=>
        string(8) "pass]word"
      }
      [2]=>
      array(2) {
        ["login"]=>
        string(5) "admin"
        ["password"]=>
        string(6) "123321"
      }
    }
    

    This code is working correctly for the others samples from your question.