0

I have a string

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

and need to explode to an array having structure

array( [0] => words,one ,[1] => words2)
4
  • @andreas I tried explode function ie, explode("," , $string); But the result is array(3) { [0]=> string(6) ""words" [1]=> string(4) "one"" [2]=> string(10) " "words2" " } Commented Jan 31, 2018 at 4:36
  • Do you expect this to have more then 2 groups? Also, will the input string always have an extra pair of quotes around the whole thing. Commented Jan 31, 2018 at 4:48
  • you can also try preg_split("/\",\"/", trim($str, '"')); Commented Jan 31, 2018 at 4:50
  • How are you creating this string ? Commented Jan 31, 2018 at 5:05

4 Answers 4

4

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

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"

2 Comments

I need the result as array(3) { [0]=> string(9) ""words,one" [1]=> string(10) " "words2" " }
There is more " than in your original string. Is that really correct?
0

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:

Comments

0

Using preg_split you can try :

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

print_r($matches);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.