Page 1 of 1

Search operators

Posted: Thu Feb 25, 2010 9:19 am
by chris7889
Post from a newB. I have a peice of code which as I understand provides the search operators. Currently it only allows for searching one word. I would like for the search to insert % wherever there is a space and at the begining and end of the search.
e.g. 'please search this' would search for '%please%search%this%' .

This may not be enough code to work from or im heading down the wrong route. If so then appologies. Any help appreciated.

Code: Select all

} else {
                            $val = CRM_Utils_Type::escape( strtolower(trim($value)), 'String' );
                            if ( $wildcard ) {
                                $val = strtolower( addslashes( $val ) );
                                $val = "%$val%";
                                $op  = 'LIKE';
                            }
                            $this->_where[$grouping][] = "{$sql} {$op} '{$val}'";
                            $this->_qill[$grouping][]  = "$field[label] $op $qillValue";
                        }
                    } 
                    continue;

Re: Search operators

Posted: Thu Feb 25, 2010 9:39 am
by AbraCadaver
You should use the appropriate *_real_escape_string() or whatever instead of addslashes unless that is what CRM_Utils_Type::escape() is doing, then you can delete the addslashes.

Code: Select all

$val = strtolower( addslashes( $val ) );
 
// works but would replace sequential spaces with multiple %
$val = str_replace( ' ', '%', $val );
 
// replaces sequential spaces with only one %
$val = preg_replace('/[ ]+/', '%', $val);
 
$val = "%$val%";

Re: Search operators

Posted: Thu Feb 25, 2010 10:15 am
by chris7889
Brilliant. That worked a treat. Thank you AbraCadaver :D

Re: Search operators

Posted: Thu Feb 25, 2010 10:50 am
by chris7889
Thank you very much for your help.

At the moment the search for 'please search this' would search for '%please%search%this%' . Meaning the result has to have all three. Is there a change that can be made so it searches for. %please% or %search% or %this% ?

Re: Search operators

Posted: Thu Feb 25, 2010 11:03 am
by AbraCadaver
chris7889 wrote:Thank you very much for your help.

At the moment the search for 'please search this' would search for '%please%search%this%' . Meaning the result has to have all three. Is there a change that can be made so it searches for. %please% or %search% or %this% ?
Something similar to this:

Code: Select all

$condition = "WHERE `field_name` LIKE '%" . implode("%' OR `field_name` LIKE '%", explode(" ", $val)) . "%'";