5
$keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white'); $strings = array( 'She had a pink dress', 'I have a white chocolate', 'I have a green balloon', 'I have a chocolate shirt', 'He had a new yellow book', 'We have many blue boxes', 'I have a magenta tie'); 

In reality the strings array is really huge (50k+ entries).

What is the best way of running search and extracting the matching strings only?

5
  • 4
    If the data comes from a database, you should filter there already. Otherwise you can use array_filter() Commented Dec 27, 2015 at 16:39
  • @Shafizadeh it's the other way round, need to check if any of the keywords exist in every string. Commented Dec 27, 2015 at 16:43
  • In each string, you mean? Otherwise your small example already gives no results. Commented Dec 27, 2015 at 16:50
  • @GolezTrol if a string contains any of the words from the keywords array then the condition is true. Commented Dec 27, 2015 at 16:52
  • 1
    @jeroen I am working on array_filter right now. :) Commented Dec 27, 2015 at 16:53

2 Answers 2

4

Use array_filter to filter the $strings array.
Split the strings into an array, then trim each word, and use array_intersect to check if the array of words contains any of the $keywords.

$result = array_filter($strings, function($val) use ($keywords) { return array_intersect( array_map('trim', explode(' ', $val)) , $keywords); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

I would rather use the use statement in you lambda function instead of the global keyword.
@flec - I really don't like use, but as the keywords probably doesn't change, there shouldn't be any issues here, so I agree, and edited.
4

The best way is to use array_filter().

$filtered_array = array_filter($strings,'filter'); function filter($a) { $keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white'); foreach ($keywords as $k) { if (stripos($a,$k) !== FALSE) { return TRUE; } } return FALSE; } 

6 Comments

Didn't know you could actually pass an array to stripos
If this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
And you can't, it throws stripos(): needle is not a string or an integer
@adeneo Avoided this problem with a loop. Not the most elegant solution, but it works.
For performance reasons I would define $keywords outside of your filter function and include it with the use statement.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.