打包转换高级搜索到的字符串数组assoc命令?

问题描述 投票:1回答:1

我不知道是否有人一个PHP包(或正确的词来搜索谷歌)的消耗高级搜索术语和将它们转换为关联数组的认识。

实施例1:

$term = 'blue birds country:england'

将被转换为类似:

[
    'country' => 'england'
    'other' => 'blue blirds'
]

实施例2:

$term = 'country:"united kingdom" blue birds month:January'

将被转换为类似:

[
    'country' => 'united kingdom',
    'month' => 'January',
    'other' => 'blue blirds'
]

我试图用的preg_match要做到这一点,但我有一个一组多个单词单个单词之间differenciating(例如group:word)和双引号内一组(例如group:"word1 word2 word3")挣扎。

php regex search term
1个回答
1
投票

使用preg_match_all()这种拆分字符串转换成各种成分。

(\w*?):(".*?"|\w*)|(\w+)将其分解成name:"values"/valuevalue部分。然后这些组装回到与适当部分的输出(核对该正则表达式的一部分已匹配的)

$term = 'blue birds country:england';
$term = 'country:"united kingdom" blue birds month:January';
print_r(splitTerms($term));

function splitTerms ( string $input )   {
    $matches = [];
    preg_match_all('/(\w*?):(".*?"|\w*)|(\w+)/', $input, $matches);
    $out = [];
    $other = [];
    // Loop over first matching group - (\w*?)
    foreach ( $matches[1] as $key => $name )    {
        if ( !empty($name) )    {
            // If name is present - add in 2nd matching group value  - (".*?"|\w*) (without quotes)
            $out[$name] = trim($matches[2][$key],'"');
        }
        else    {
            // Otherwise use 3rd matching group - (\w+)
            $other[] = $matches[3][$key];
        }
    }

    if ( count($other) > 0 )    {
        $out['other'] = implode(" ", $other);
    }

    return $out;
}

这给...阵

(
    [country] => united kingdom
    [month] => January
    [other] => blue birds
)
© www.soinside.com 2019 - 2024. All rights reserved.