我正在使用PHP建立网站。
我正在使用preg_split()
分隔看起来像+word1 -word2 -"word word"
的给定字符串。但是我需要以下形式的它们:+word1
,-word2
,+"word word"
。
当前,我有这个:
$words = preg_split("/[\s\"]*\"([^\"]+)\"[\s\"]*|" . "[\s\"]*'([^']+)'[\s\"]*|" . "[\s\"]+/", $search_expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
但是它没有按我希望的那样工作:我需要以这种方式来使它工作:+word1 -word2 '-"word word"'
。
有人有更好的正则表达式或主意吗?
[一种选择是从双引号匹配到双引号,并且不要使用SKIP FAIL对该匹配进行拆分。然后匹配1个以上水平空白字符以进行分割。
"[^"]+"(*SKIP)(*FAIL)|\h+
例如
$search_expression = '+word1 -word2 -"word word"';
$words = preg_split("~\"[^\"]+\"(*SKIP)(*FAIL)|\h+~", $search_expression);
print_r($words);
输出
Array
(
[0] => +word1
[1] => -word2
[2] => -"word word"
)
一个带有贪婪?
的简单表达式可以匹配您的示例:
preg_match_all('/[+-][^+-]+ ?/', $search_expression, $matches);
print_r($matches[0]);