开发者

Mirror SQL's LIKE functionality for a PHP array?

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 th开发者_如何学Pythonat will return all the possible matches from the array?


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜