Magento – Ignoring special characters during catalog search

catalogsearchmagento-1.9

I want to ignore special characters while catalog search. When a user enters any special character in the search box, the search shall find results for the combination both with and without special characters, even a whitespace. e.g searching for 122hj7 12w will search for 122hj7 12w results as well as 122hj712w results.

Best Answer

Need to some change in helper file app\code\core\Mage\CatalogSearch\Helper\Data.php

from

public function getQueryText()
{
    if (!isset($this->_queryText)) {
        $this->_queryText = $this->_getRequest()->getParam($this->getQueryParamName());   
        if ($this->_queryText === null) {
            $this->_queryText = '';
        } else {
            /* @var $stringHelper Mage_Core_Helper_String */
            $stringHelper = Mage::helper('core/string');
            $this->_queryText = is_array($this->_queryText) ? ''
                : $stringHelper->cleanString(trim($this->_queryText));

            $maxQueryLength = $this->getMaxQueryLength();
            if ($maxQueryLength !== '' && $stringHelper->strlen($this->_queryText) > $maxQueryLength) {
                $this->_queryText = $stringHelper->substr($this->_queryText, 0, $maxQueryLength);
                $this->_isMaxLength = true;
            }
        }
    }
    return $this->_queryText;
}

To

 public function getQueryText()
    {
        if (!isset($this->_queryText)) {
            $this->_queryText = $this->_getRequest()->getParam($this->getQueryParamName());   
           $this->_queryText =  preg_replace('/[^A-Za-z0-9\-\']/', '', $this->_queryText);  // escape apostraphe
            if ($this->_queryText === null) {
                $this->_queryText = '';
            } else {
                /* @var $stringHelper Mage_Core_Helper_String */
                $stringHelper = Mage::helper('core/string');
                $this->_queryText = is_array($this->_queryText) ? ''
                    : $stringHelper->cleanString(trim($this->_queryText));

                $maxQueryLength = $this->getMaxQueryLength();
                if ($maxQueryLength !== '' && $stringHelper->strlen($this->_queryText) > $maxQueryLength) {
                    $this->_queryText = $stringHelper->substr($this->_queryText, 0, $maxQueryLength);
                    $this->_isMaxLength = true;
                }
            }
        }
        return $this->_queryText;
    }

We have add only one line code in above function $this->_queryText = preg_replace('/[^A-Za-z0-9\-\']/', '', $this->_queryText);

Note: first move core file to local app\code\local\Mage\CatalogSearch\Helper\Data.php after add above change or rewrite a helper class Mage_CatalogSearch_Helper_Data to local click here to rewrite helper steps