Reputation: 471
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
Reputation: 1633
Using preg_split you can try :
$str = '"words,one","words2"';
$matches = preg_split("/\",\"/", trim($str, '"'));
print_r($matches);
Upvotes: 0
Reputation: 1642
Assuming the the input string can be broken down as follows:
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
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
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);
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