Complex String Comparisons
<p>I'm trying to write a function in PHP that takes an array of strings (<code>needle</code>) and performs a comparison against another array of strings (<code>haystack</code>). The purpose of this function is to quickly deliver matching strings for an AJAX search, so it needs to be as fast as possible.</p>

<p>Here's some sample code to illustrate the two arrays;</p>

<pre><code>$needle = array('ba','hot','resta');

$haystack = array(
    'Southern Hotel',
    'Grange Restaurant &amp; Hotel',
    'Austral Hotel',
    'Barsmith Hotel',
    'Errestas'
);
</code></pre>

<p>Whilst this is quite easy in itself, the aim of the comparison is to count how many of the <code>needle</code> strings appear in the <code>haystack</code>.</p>

<p>However, there are three constraints;</p>

<ol>
<li>The comparison is case-insensitive</li>
<li>The <code>needle</code> must only match characters at the
beginning of the word. For example,
"hote" will match "Hotel", but "resta"
will not match "Errestas".</li>
<li>We want to count the number of matching <code>needles</code>, not the number of <code>needle</code> appearances. If a place is named "Hotel Hotel Hotel", we need the result to be <code>1</code> not <code>3</code>.</li>
</ol>

<p>Using the above example, we'd expect the following associative array as a result:</p>

<pre><code>$haystack = array(
    'Southern Hotel' =&gt; 1,
    'Grange Restaurant &amp; Hotel' =&gt; 2,
    'Austral Hotel' =&gt; 1,
    'Barsmith Hotel' =&gt; 2,
    'Erresta'  =&gt; 0
);
</code></pre>

<p>I've been trying to implement a function to do this, using a <code>preg_match_all()</code> and a regexp which looks like <code>/(\A|\s)(ba|hot|resta)/</code>. Whilst this ensures we only match the beginning of words, it doesn't take into account strings which contain the same <code>needle</code> twice.</p>

<p>I am posting to see whether someone else has a solution?</p>
