-3

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

b:Blue | y:Yellow | r:Red

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

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

我对php很熟悉,除了爆炸的东西……</p>

4

4 回答 4

3

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

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(). 之后,您需要从值中修剪任何尾随和前导空格。

于 2013-07-24T08:37:39.527 回答
1
$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);
于 2013-07-24T08:28:41.713 回答
1

尝试这样的事情:

$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
)
*/
于 2013-07-24T08:29:59.597 回答
0

首先爆炸| 之后

// 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)
*/
于 2013-07-24T08:32:36.040 回答