gpt4 book ai didi

PHP 从字符串中获取搜索词数组

转载 作者:行者123 更新时间:2023-12-02 08:41:09 26 4
gpt4 key购买 nike

是否有一种简单的方法来解析字符串以查找包括否定词在内的搜索词?

'this -that "the other thing" -"but not this" "-positive"' 

将更改为

array(
"positive" => array(
"this",
"the other thing",
"-positive"
),
"negative" => array(
"that",
"but not this"
)
)

因此这些术语可用于搜索。

最佳答案

下面的代码将解析您的查询字符串并将其分为肯定搜索词和否定搜索词。

// parse the query string
$query = 'this -that "-that" "the other thing" -"but not this" ';
preg_match_all('/-*"[^"]+"|\S+/', $query, $matches);

// sort the terms
$terms = array(
'positive' => array(),
'negative' => array(),
);
foreach ($matches[0] as $match) {
if ('-' == $match[0]) {
$terms['negative'][] = trim(ltrim($match, '-'), '"');
} else {
$terms['positive'][] = trim($match, '"');
}
}

print_r($terms);

输出

Array
(
[positive] => Array
(
[0] => this
[1] => -that
[2] => the other thing
)

[negative] => Array
(
[0] => that
[1] => but not this
)
)

关于PHP 从字符串中获取搜索词数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com