Search code examples
phpstringtext-extractiontext-parsing

Parse a formatted string containing comma-separated key=value expressions


I have a string comma separated where I want to get 2 values in variables. How can I accomplish it.

$responseData = "Data: invoice=1216,card=AMEX";

I am looking for value of Invoice and Card.

I tried using instring but not getting value I want.


Solution

  • sscanf()

    You can use sscanf() to achieve this result.

    sscanf() takes the same format as printf(), allowing you to provide a variable and expected format string, and will return the matching results.

    For example:

    list($invoice, $card) = sscanf($responseData, "Data: invoice=%d,card=%s");
    var_dump($invoice); // int(1216)
    var_dump($card);    // string(4) "AMEX"
    

    Community wiki of Mark Baker's answer in the comments above.

    explode()

    You can also do this manually by breaking up the string by delimiters with explode(). The Data: component is irrelevant, so trim it off, then split by commas, then split by = to get a key => value pair.

    For example:

    // Remove the Data: component
    $responseData = ltrim($responseData, 'Data: ');
    
    $example = array();
    // Split by commas
    foreach (explode(',', $responseData) as $value) {
        // Split by equals
        list ($k, $v) = explode('=', $value);
        $example[$k] = $v;
    }
    
    var_dump($example);
    // array(2) {
    //   ["invoice"]=>
    //   string(4) "1216"
    //   ["card"]=>
    //   string(4) "AMEX"
    // }