Question

I have a problem with str_getcsv function for PHP.

I have this code:

<?php
$string = '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=714000,RESOLUTION=640x480,CODECS="avc1.77.30, mp4a.40.34"';

$array = str_getcsv($string, ",", '"');

print_r($array);

Which should return:

Array
(
    [0] => #EXT-X-STREAM-INF:PROGRAM-ID=1
    [1] => BANDWIDTH=714000
    [2] => RESOLUTION=640x480
    [3] => CODECS=avc1.77.30, mp4a.40.34
)

But instead, it is returning:

Array
(
    [0] => #EXT-X-STREAM-INF:PROGRAM-ID=1
    [1] => BANDWIDTH=714000
    [2] => RESOLUTION=640x480
    [3] => CODECS="avc1.77.30
    [4] =>  mp4a.40.34"
)

Cause it is ignoring the enclosure of the last parameter: CODECS and is spliting also that information. I'm using str_getcsv instead of just doing explode(",", $string) precisely for that reason (that function should respect the enclosure) but it is working the same as explode will do it.

The code being executed: http://eval.in/17471

Was it helpful?

Solution

The enclosure (third) parameter does not have quite that effect. The enclosure character is treated as such only when it appears next to the delimiter.

To get your desired output, the input would need to be

#EXT-X-STREAM-INF:PROGRAM-ID=1,...,"CODECS=avc1.77.30, mp4a.40.34"

See it in action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top