我不知道是否有人一个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"
)挣扎。
使用preg_match_all()
这种拆分字符串转换成各种成分。
(\w*?):(".*?"|\w*)|(\w+)
将其分解成name:"values"/value
和value
部分。然后这些组装回到与适当部分的输出(核对该正则表达式的一部分已匹配的)
$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
)