如何将具有不同分隔符的字符串拆分为数组


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

如何将具有不同分隔符的字符串拆分为数组?

即转换为:'web:427;法语:435'到这个:

'web' => 427,
'french' => 435

只要您的字符串不包含&=,这将起作用。

$str = 'web:427;French:435';
$str = str_replace([';', ':'], ['&', '='], $str);
parse_str($str, $array);
print_r($array);

正如mario所指出的,如果你不介意使用regex,你可以修改这个答案来满足你的需求。如果您希望在不使用regex的情况下执行此操作,请尝试以下操作:(只要您的字符串中的变量名或值中没有:;,就会起作用)

$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);