title: Expanded 'Contains' Function - PHP String Space-Delimited Query with Multiple Comma-Separated Keyword Needle
body: <p>I'm working on a search / advertising system that matches a given ad group with keywords. Query is the string that is the search string, what we're looking for is the best and most efficient way to enhance the simple 'contains' script below that searches through the query, but looks for keyword matches on an AND (&amp;&amp;) explosion. With this script one could build either 'IF' or it could be a "CASE" below is the pseudo code:</p>
  
  <pre><code>$query = "apple berry tomato potato":
  
  if contains ($query,"tomato")  {   }
  if contains ($query,"potato,berry")  {   }
  if contains ($query,"apple,berry")  {  }
  
  else i.e. none of the above do {  }
  </code></pre>
  
  <p>the function contains would use strpos but would also use some combination of explode to distinguish words that are separated by commas.  So Apple,berry would be where a string contains the list of keywords separated by commas.</p>
  
  <p>What would be the best way to write a contains script that searches through the query string and matches against the comma-separated values in the second parameter?  Love your ideas. Thanks.</p>
  
  <p>Here is a the classic simple 'contains' function, but it doesn't handle the comma-separated AND Explosion - it only works with single words or phrases</p>
  
  <pre><code>function contains($haystack,$needle)
  {
      return strpos($haystack, $needle) !== false;
  }
  </code></pre>
  
  <p>Note : the enhanced contains function should scan for the match of the string on an AND basis. If commas exist in the $needle it needs to include all of the keywords to show a match. The simple contains script is explained on this post <a href="https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word-in-php?rq=1">Check if String contains a given word</a> . What I'm looking for is an expanded function by the same name that also searches for multiple keywords, not just a single word.</p>
  
  <p>The $query string will always be space delimited.
  The $needle string will always be comma delimited, or it could be delimited by spaces. </p>
  
  <p>The main thing is that the function works in multiple directions</p>
  
  <p>Suppose the $query = 'business plan template'
  or $query = 'templates for business plan'</p>
  
  <p>if you ran contains ($query,"business plan")
  or contains ($query,"business,plan") both tests would show a match. The sequence of the words should not matter.</p>