用于将高级搜索字符串转换为assoc数组的软件包?

时间:2019-02-04 10:10:26

标签: php regex search term

我想知道是否有人知道使用PHP软件包(或搜索Google的正确术语)来使用高级搜索词并将其转换为关联数组。

示例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做到这一点,但是我很难区分一个组中的单个单词(例如group:word)和双引号中的一组多个单词(例如group:"word1 word2 word3")。 / p>

1 个答案:

答案 0 :(得分: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
)