【问题标题】:how can I split a string with different delimiters into an array? [duplicate]如何将具有不同分隔符的字符串拆分为数组? [复制]
【发布时间】:2013-07-29 23:37:31
【问题描述】:

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

即把这个:'web:427;French:435' 转换成这个:

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

【问题讨论】:

  • 什么算作分隔符?
  • 使用正则表达式或strtrparse_str

标签: php arrays string


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    正如 mario 所指出的,如果您不介意使用正则表达式,您可以修改 this answer 以满足您的需要。如果您希望不使用正则表达式,请尝试以下操作:(只要您的字符串在变量名称或值中没有 :; 就可以使用)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2014-04-16
      相关资源
      最近更新 更多