我正在尝试使用可以将特定关键字与特定字段相关联的标记进行高级搜索,如下所示:
搜索:测试消息状态:已关闭用户:约翰
想知道将字符串解析为一个好的数组的最佳方法是什么:
[“search”=> “测试消息”,“状态”=> “关闭”,“用户”=> “约翰”]
目前我这样做:
$parse = explode(':', $_REQUEST['q']);
$parsed = [];
foreach($parse AS $key => $value) {
if($key == (count($parse) - 1))
break;
$next = explode(' ', $parse[($key + 1)]);
$last = array_pop($next);
$next = implode(' ', $next);
$parse[($key + 1)] = $last;
$parsed[$parse[$key]] = !empty($next) ? $next : $last;
}
答案 0 :(得分:0)
这是一个替代解决方案,但我很谨慎,如果我们能用regexp做到这一点是最优雅的,我只是无法弄清楚这个模式:
$string = "search: test message status: closed user: john";
$pieces = explode(' ', $string);
$values = array();
$array = array();
foreach ($pieces as $piece) {
if (strpos($piece, ":") !== false) {
if (count($values)) {
$array[$key] = join(" ", $values);
}
$key = rtrim($piece, ":");
$values = array();
} else {
$values[] = $piece;
}
}
$array[$key] = join(" ", $values);
var_dump($array);
输出
array
'search' => string 'test message' (length=12)
'status' => string 'closed' (length=6)
'user' => string 'john' (length=4)
修改强>
根据tntu评论,这是一个带有正则表达式的版本:
$string = "search: test message status: closed user: john";
$matches = array();
preg_match_all('/(([a-z]+):([a-z0-9 ]+(?![a-z:])))+/is', $string, $matches);
$i = 0;
foreach ($matches[2] as $key) {
if (isset($matches[3][$i])) {
$array[$key] = trim($matches[3][$i]);
} else {
break;
}
$i++;
}