3

I need to cast $string = ("one","two","three,subthree","four") into PHP array like.

$data[0] => "one",
$data[1] => "two",
$data[2] => "three,subthree",
$data[3] => "four"

The issue is that the delimiter in 3rd variable contains comma so explode function is making the string into 5 variables instead of 4.

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
Wajahat
  • 53
  • 7

5 Answers5

3

You can convert the string to JSON string and then decode like this

$string = '("one","two","three,subthree","four")';
$string = str_replace(['(', ')'], ['[', ']'], $string);

$array = json_decode($string, true);
print_r($array);

Working demo.


Edit:

If you have possibilities to have brackets [( or )] in string, you can trim by brackets [( or )] and explode by the delimiter ",". Example:

$string = '("one","two","three,subthree","four")';
$string = trim($string, ' ()');

$array = explode('","', $string);
print_r($array);

Another way is to use preg_match_all() by the patter ~"([^"])+"~

$string = '("one","two","three,subthree","four")';
preg_match_all('~"([^"]+)"~', $string, $array);
print_r($array[0]);

Regex explanation:

  • " matches a double quote
  • ([^"]+) capturing group
  • [^"] any characters except double quote
  • + one or more occurrence
  • " matches a double quote
MH2K9
  • 11,951
  • 7
  • 32
  • 49
3

Here's a shorter version to do that:

$string = '("one", "two,three")';

preg_match_all('/"([^"]+)"/', $string, $string);

echo "<pre>";
var_dump($string[1]);

Output:

array(2) {
 [0]=>
  string(3) "one"
 [1]=>
 string(9) "two,three"
}
Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
1

You can use substr to remove the first (" and ") and then use explode:

$string = '("one","two","three,subthree","four")';
$s = substr($string,2,-2); 
// now $s is: one","two","three,subthree","four
print_r(explode('","', $s));

Which outputs:

(
    [0] => one
    [1] => two
    [2] => three,subthree
    [3] => four
)

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
0

You can use explode with trim

$string = '("one","two","three,subthree","four")';
print_r(explode('","',trim($string,'"()')));

Working example : https://3v4l.org/4ZERb

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

A simple way which does the processing of quotes for you is to use str_getcsv() (after removing the start and end brackets)...

$string = '("one","two","three,subthree","four")';
$string = substr($string, 1, -1);
print_r(str_getcsv($string));

gives

Array
(
    [0] => one
    [1] => two
    [2] => three,subthree
    [3] => four
)

Main thing is that it will also work with...

$string = '("one","two","three,subthree","four",5)';

and output

Array
(
    [0] => one
    [1] => two
    [2] => three,subthree
    [3] => four
    [4] => 5
)
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55