3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data1 = '"slug,1", slug 2, test, "slug, 3", " ", "", ",",'; $data2 = 'foo, bar'; $data3 = 'foo, bar, "'; function is_valid_plugin_slug($slug) { return trim($slug, ", \t\n\r\0\x0B") !== ''; } function str_getcsv_augmented($data) { $plugins = str_getcsv( str_replace('""', '', $data ) ); return array_filter($plugins, 'is_valid_plugin_slug'); } function extract_required_plugins_from_header($required) { if (!$required || (substr_count($required, '"') < 2)) { return $required ? array_filter(array_map('trim', explode(',', str_replace('"', '', $required)))) : []; } $required = str_replace('""', '', $required); preg_match_all('#"([^"]+)"#', $required, $matches); $slugs = array_filter(array_map('trim', explode(',', strtr($required, array_fill_keys($matches[0], ''))))); return array_merge(array_filter($matches[1], 'is_valid_plugin_slug'), $slugs); } echo "Bare str_getcsv:\n"; var_dump( str_getcsv( $data1 ), str_getcsv( $data2 ), str_getcsv( $data3 ) ); echo "\n\nstr_getcsv with filtering:\n"; var_dump( str_getcsv_augmented( $data1 ), str_getcsv_augmented( $data2 ), str_getcsv_augmented( $data3 ) ); echo "\n\nextract_required_plugins_from_header:\n"; var_dump( extract_required_plugins_from_header( $data1 ), extract_required_plugins_from_header( $data2 ), extract_required_plugins_from_header( $data3 ) );
Output for 7.3.0 - 7.3.31, 7.4.0 - 7.4.25, 8.0.0 - 8.0.12, 8.1rc1 - rc3
Bare str_getcsv: array(8) { [0]=> string(6) "slug,1" [1]=> string(7) " slug 2" [2]=> string(5) " test" [3]=> string(7) "slug, 3" [4]=> string(1) " " [5]=> string(0) "" [6]=> string(1) "," [7]=> string(0) "" } array(2) { [0]=> string(3) "foo" [1]=> string(6) " bar" } array(3) { [0]=> string(3) "foo" [1]=> string(4) " bar" [2]=> string(1) "" } str_getcsv with filtering: array(4) { [0]=> string(6) "slug,1" [1]=> string(7) " slug 2" [2]=> string(5) " test" [3]=> string(7) "slug, 3" } array(2) { [0]=> string(3) "foo" [1]=> string(6) " bar" } array(2) { [0]=> string(3) "foo" [1]=> string(4) " bar" } extract_required_plugins_from_header: array(4) { [0]=> string(6) "slug,1" [1]=> string(7) "slug, 3" [2]=> string(6) "slug 2" [3]=> string(4) "test" } array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" } array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" }

preferences:
31.83 ms | 462 KiB | 5 Q