I finally have developed a solution for this problem which involved a few PHP statements utilizing regular expressions. Below is the final function.
This function is part of a class which is why it begins with "public".
public function SearchString_ToArr($SearchString) {
/*
Purpose
Used to parse the specified search string into an array of search terms.
Search terms are delimited by <0 or more whitespace><optional comma><0 or more whitespace>
Parameters
SearchString (string) = The search string we're working with.
Return (array)
Returns an array using the following rules to parse the specified search string:
- Each search term from the search string is converted to a single element in the returned array.
- Search terms are delimited by whitespace and/or commas, or they may be double quoted.
- Double-quoted search terms may contain multiple words.
Unquoted Search Terms:
- These are delimited by any number of whitespace characters or commas in the search string.
- These have all leading and trailing whitespace trimmed.
Quoted Search Terms:
- These are surrounded by double-quotes in the search string.
- These retain leading and trailing double-quotes in the returned array.
- These have all leading and trailing whitespace trimmed.
- These may contain whitespace.
- These have all containing whitespace converted into a single space.
- If these are zero-length or contain only whitespace, they are not included in the returned array.
Example 1:
SearchString = ' "" one " two three " four "five six" " " '
Returns {"one", ""two three"", "four", ""five six""}
Notes The leading whitespace before the first "" is not returned.
The first quoted phrase ("") is empty so it is not returned.
The term "one" is returned with leading and trailing whitespace removed.
The phrase "two three" is returned with leading and trailing whitspace removed.
The phrase "two three" has containing whitespace converted to a single space.
The phrase "two three" has leading and trailing double-quotes retained.
...
Version History
1.0 2013.09.18 Tested by Russ Tanner on PHP 5.3.10.
*/
$r = array();
$Matches = array();
// Split the search string into an array based on whitespace, commas, and double-quoted phrases.
preg_match_all('/(?:"([^"]*)"|([^\s",]+))/', $SearchString, $Matches);
// At this point:
// 1. all quoted strings have their own element and begin/end with the quote character.
// 2. all non-quoted strings have their own element and are trimmed.
// 3. empty strings are omitted.
// Normalize quoted elements...
// Convert all internal whitespace to a single space.
$r = preg_replace('/\s\s+/', ' ', $Matches[0]);
// Remove all whitespace between the double-quotes and the string.
$r = preg_replace('/^"\s+/', '"', $r);
$r = preg_replace('/\s+"$/', '"', $r);
return $r;
}