-2

How can I split a string with different delimiters into an array?

i.e. convert this: 'web:427;French:435' to this:

'web' => 427,
'french' => 435
Sean Kimball
  • 4,506
  • 9
  • 42
  • 73

2 Answers2

1

This will work as long as your string does not contain & or =.

$str = 'web:427;French:435';
$str = str_replace([';', ':'], ['&', '='], $str);
parse_str($str, $array);
print_r($array);
str
  • 42,689
  • 17
  • 109
  • 127
0

As mario pointed out, if you don't mind using regex you can amend this answer to fit your needs. If you wish to do it without regex try this: (will work as long as your string doesn't have : and ; inside the variable names or values)

$str = 'web:427;French:435';
$array = explode(';',$str); // first explode by semicolon to saparate the variables

$result = array();
foreach($array as $key=>$value){
    $temp = explode(':',$value); // explode each variable by colon to get name and value
    $array[$temp[0]]= $temp[1];
}

print_r($result);
Community
  • 1
  • 1
Yotam Omer
  • 15,310
  • 11
  • 62
  • 65