雖然這不是一個特別優雅的解決方案,但它應該工作得很好。本質上,你首先替換引用的字符串,找到搜索條件,然後將其替換回來。
$search_term = ' "full name"="john smith" city="london" foo bar baz ';
$replace = array();
// find all quoted strings
preg_match_all('#"[^"]+"#', $search_term, $matches);
// and replace them with something temporary
foreach ($matches[0] as $k => $match) $replace[$match] = "quo" . $k . "ted";
$search_term_without_quotes = str_replace(array_keys($replace), array_values($replace), $search_term);
$terms = explode(' ', $search_term_without_quotes);
$array = array();
$general = "";
foreach ($terms as $term) {
// replace it back (notice the reversed array_values and array_keys
$term = str_replace(array_values($replace), array_keys($replace), $term);
// explode into two fields
// if an = can be in the first quoted term you need to move the replacing further down
$term = explode("=", $term, 2);
if (count($term) == 1) {
$general .= " " . trim($term[0], '"');
} else {
$array[trim($term[0], '"')] = trim($term[1], '"');
}
}
print_r($array);
print_r($general);
這給了你:
Array
(
[full name] => john smith
[city] => london
)
foo bar baz
不幸的是,這不適用於像'foo「全名」=「john smith」bar city =「london」baz'(我的)那樣的字符串。不過,可能相應地調整正則表達式。 – akirk
是的,順序會影響輸出,就像akirk說的那樣。 – trafalgar
@akirk:是的,你說得對。 – Toto