tags:

views:

73

answers:

2

At the minute I have a page with an AJAX script that searches a database with LIKE '%search term from input box%'.

I need to modify it so that instead of searching the database it searches an array (that has been constructed from two tables - I can't use a JOIN because there's a bit more to it than that).

How do I go about creating a fuzzy search function in PHP that will return all the possible matches from the array?

+7  A: 

you want preg_grep

e.g.

$arr = array("tom jones", "tom smith", "bob jones", "jon smith");
$results = preg_grep("/jones/",$arr);

$results will now contain two elements, "tom jones" and "bob jones"

Jonathan Fingland
Good solution! But $results = preg_grep("%jones%",$arr); would be a little bit more LIKEly ;)
powtac
I do indeed want preg_grep, thank-you =)
bcmcfc
+1  A: 

you could just loop over the array and use strpos to find the matching elements

foreach( $arr as $value ) {
   if ( strpos($value, 'searchterm') !== FALSE ) {
      // Match
   }
}

You could use a regular expression for more advanced searching, but strpos will be faster if you are just trying to do a simple LIKE '%term%' type search.

Eric Petroelje
this will not recursively iterate over a multi-dimensional array, however.
cballou
except that would fail for wildcards in the middle e.g. like %dav%d%
Jonathan Fingland