将字符串解析为数组,其中键由冒号分隔

时间:2015-08-06 02:34:53

标签: php arrays parsing

我正在尝试将字符串解析为数组以进行搜索。就像我有这个字符串:

$string = 'is:issue is:open user:john Hello world';

我希望这个数组像:

array(
    'is'        => array('issue', 'open'),
    'user'      => 'john',
    'q'         => 'Hello world'
);

我尝试使用explode,但无法弄清楚如何捕获冒号分隔的单词和最后一个查询字符串。

由于

1 个答案:

答案 0 :(得分:0)

输入格式并不理想,但它不应该太难。我们按空格分割,将每个部分作为一对处理,当我们到达无法处理的部分时,假设它是查询。

这假设查询总是最后一次。

function searchParse($str) {

    $output = array();

    // split by space
    $bits = explode(' ', $str);

    // process pairs
    foreach($bits as $id=>$pair) {

        // split the pair
        $pairBits = explode(':', $pair);

        // this was actually a pair
        if(count($pairBits) == 2) {

            // use left part of pair as index and push right part to array
            $output[$pairBits[0]][] = $pairBits[1];

            // remove this pair from $bits
            unset($bits[$id]);
        }

        // not a pair, presumably reached the query
        else {

            // exit the loop
            break;
        }
    }

    // rebuild query with remains of $bits
    $output['q'] = implode(' ', $bits);

    return $output;
}

测试:

$string = 'is:issue is:open user:john Hello world';
$r = searchParse($string);
print_r($r);

输出:

Array
(
    [is] => Array
        (
            [0] => issue
            [1] => open
        )

    [user] => Array
        (
            [0] => john
        )

    [q] => Hello world
)