PHP多重分解键值数组


PHP multiple explode key value array

嘿,伙计们,我有一个字符串,看起来像这样:

b:Blue | y:Yellow | r:Red

并希望将此字符串转换为具有键值的数组。

array(
  'b' => 'Blue',
  'y' => 'Yellow',
  'r' => 'Red'
);

我对php非常熟悉,除了爆炸的东西…

与其尝试拆分,不如匹配它:

preg_match_all('/('w):('w+)/', 'b:Blue | y:Yellow | r:Red', $matches);
print_r(array_combine($matches[1], $matches[2]));

它匹配一个字母数字字符,后面跟着一个冒号,然后是更多的字母数字字符;这两个部分都被捕获在存储器组中。最后,将第一存储器组与第二存储器组组合。

一种更受黑客攻击的方法是:

parse_str(strtr('b:Blue | y:Yellow | r:Red', ':|', '=&'), $arr);
print_r(array_map('trim', $arr));

它将字符串转换为类似application/x-www-form-urlencoded的东西,然后用parse_str()对其进行解析。之后,您需要从值中修剪任何尾随空格和前导空格。

$string = "b:Blue | y:Yellow | r:Red";
//split string at ' | '
$data = explode(" | ", $string);
$resultArray = array();
//loop through split result
foreach($data as $row) {
    //split again at ':'
    $result = explode(":", $row);
    //add key / value pair to result array
    $resultArray[$result[0]] = $result[1];
}
//print result array
print_r($resultArray);

试试这样的东西:

$str = "b:Blue | y:Yellow | r:Red";
// Split on ' | ', creating an array of the 3 colors 
$split = explode(' | ', $str);
$colors = array();
foreach($split as $spl)
{
    // For each color now found, split on ':' to seperate the colors.
    $split2 = explode(':', $spl);
    // Add to the colors array, using the letter as the index. 
    // (r:Red becomes 'r' => 'red')
    $colors[$split2[0]] = $split2[1];
}
print_r($colors);
/*
Array
(
    [b] => Blue
    [y] => Yellow
    [r] => Red
)
*/

首先用|爆炸,然后用爆炸

// I got the from php.net
function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}
$string = "b:Blue | y:Yellow | r:Red"; // Your string
$delimiters = array(" | ", ":"); // | important that it is first
$matches = multiexplode($delimiters, $string);
/*
array (size=3)
  0 => 
    array (size=2)
      0 => string 'b' (length=1)
      1 => string 'Blue' (length=4)
  1 => 
    array (size=2)
      0 => string 'y' (length=1)
      1 => string 'Yellow' (length=6)
  2 => 
    array (size=2)
      0 => string 'r' (length=1)
      1 => string 'Red' (length=3)
*/