Search code examples
phpstringcsvtext-extractiontext-parsing

Parse a CSV string and assign each value to a variable


I have this kind of string.

'"asdfasdf","123456", this is a message. OK'

What I want to do is declare variables according to the first and second quoted values and then the rest of the message until the OK. (note: the length of the string inside the '' is not consistent)

$First = "asdfasdf"
$Second = "123456"
$Message = "this is a message"

Is this even possible? Is there something like " "$First","$Second", "$Message" OK " kind of way?


Solution

  • You can use regular expressions, like this:

    Code

    $raw = '"asdfasdf","123456", this is a message. OK'; // this is your raw text
    preg_match('/^"(?P<first>[^"]+)","(?P<second>[^"]+)",\s+(?P<message>.+?) OK/', $raw, $matches); // this looks for the pattern you defined and stores the matches in $matches
    print_r($matches); // this just dumps out the array of matching substrings
    

    Output

    Array
    (
        [0] => "asdfasdf","123456", this is a message. OK
        [first] => asdfasdf
        [1] => asdfasdf
        [second] => 123456
        [2] => 123456
        [message] => this is a message.
        [3] => this is a message.
    )
    

    You can access the individual substrings as, for example, $matches['first'], $matches['second'], or $matches['message'].

    PHP Demo

    Regex Demo