title: How can I bundle search terms into more efficient queries?
body: <p>I need to convert a list of search terms into the most efficient set of combined search terms. Any word or quoted phrase can be separated by an OR. Many terms can be combined within parentheses. ANDs can also be used.</p>
  
  <p>For example, <code>foo bar</code> and <code>boo bar</code> share <code>bar</code>, so instead of two different search terms, the can be combined as <code>(foo OR boo) AND bar</code>.</p>
  
  <p>Here's what the algorithm needs to do. Given this data set:</p>
  
  <pre><code>foo bar
  boo bar
  goo bar
  hoo doo
  foo manchu
  moo bar
  too bar
  foo fighters
  "blue kazoo" bar
  baz
  qux
  quux
  </code></pre>
  
  <p>I want to get the following back:</p>
  
  <pre><code>(foo OR boo OR goo OR moo OR too OR "blue kazoo") AND bar
  foo AND (manchu OR fighters)
  hoo doo
  baz OR qux OR quux
  </code></pre>
  
  <p>This does not work:</p>
  
  <pre><code>(foo bar) OR (boo bar) OR (goo bar) OR (foo manchu)
  </code></pre>
  
  <p>I'll be working in PHP, but I'll take the answer in pseudo-code, PHP or I'll convert from major languages.</p>