Ann
Ann

Reputation: 471

Explode a CSV string with quoted substrings to create a flat array

I have a string

string(22) ""words,one","words2""

and need to explode to an array having structure

array( [0] => words,one ,[1] => words2)

Upvotes: 0

Views: 89

Answers (4)

Ravi Sachaniya
Ravi Sachaniya

Reputation: 1633

Using preg_split you can try :

$str = '"words,one","words2"';
$matches = preg_split("/\",\"/", trim($str, '"'));

print_r($matches);

Upvotes: 0

SH-
SH-

Reputation: 1642

Assuming the the input string can be broken down as follows:

  • The surrounding double-quotes are always present and consist of one double-quote each.
  • "words,one","words2" is left after removing the surrounding double-quotes.

We can extract a csv formatted string that fgetcsv can parse.


Trimming the original and wrapping it in a stream allows us to use fgetcsv. See sample code on eval.in

$fullString= '""words,one","words2""';
$innerString = substr($fullString, 1, -1)
$tempFileHandle = fopen("php://memory", 'r+');
fputs($tempFileHandle , $innerString);
rewind($tempFileHandle);
$explodedString = fgetcsv($tempFileHandle, 0, ',', '"'); 
fclose($tempFileHandle);

This method also supports other similarly formatted strings:

Upvotes: 0

hcoat
hcoat

Reputation: 2643

To continue on the explode option you mentioned trying, you could try the following:

$str = '"words,one","words2"';
$arr = explode('","', trim($str, '"'));

print_r($arr);

Notice the trim to remove the beginning and ending quote marks, while explode uses the inner quote marks as part of the delimiter.

Output

Array
(
    [0] => words,one
    [1] => words2
)

Upvotes: 4

Andreas
Andreas

Reputation: 23958

I assume your "" is a typo for "\" or '".
I use regex to capture what is inside of " with (.*?) where the ? means be lazy.
I escape the " with \" to make it read them literal.
You will have your words in $m[1].

$str = '"words,one","words2"';

Preg_match_all("/\"(.*?)\"/", $str, $m);

Var_dump($m);

https://3v4l.org/G4m4f

In case that is not a typo you can use this:

Preg_match_all("/\"+(.*?)\"+/", $str, $m);

Here I add a + to each of the " which means "there can be more than one"

Upvotes: 1

Related Questions