Magento Collection Filtering – Filtering Results Using LIKE

attributescollection-filteringcollection;

Consider these three "haystack" strings:

a) foo bar

b) welcome to foo bar industries

c) foo barer

And now my "needle":

foo bar

(Heh)

I would like my filter to match my needle with haystack strings a & b but not c. I have tried:

$collection->addAttributeToFilter('name', array('like' => '%'.$needle.'%'));

But the above matches with c.

I also tried:

$collection->addAttributeToFilter('name', array('like' => '% '.$needle.' %')); // Note the spaces

The above only matches with b.

Any help is much appreciated.

Best Answer

Give this a try and see if it fits:

$collection->addAttributeToFilter('name', array(
    array('like' => '% '.$needle.' %'), //spaces on each side
    array('like' => '% '.$needle), //space before and ends with $needle
    array('like' => $needle.' %') // starts with needle and space after
));

Passing the second parameter as an array of arrays will concatenate the conditions using OR