I have 2 arrays. One with bad keywords and the other with names of sites.
$bad_keywords = array('google',
'twitter',
'facebook');
$sites = array('youtube.com', 'google.com', 'm.google.co.uk', 'walmart.com', 'thezoo.com', 'etc.com');
Simple task: I need to filter through the $sites
array and filter out any value that contains any keyword that is found in the $bad_keywords
array. At the end of it I need an array with clean values that I would not find any bad_keywords occurring at all.
I have scoured the web and can't seem to find a simple easy solution for this. Here are several methods that I have tried:
1. using 2 foreach
loops (feels slower - I think using in-built php functions will speed it up)
2. array_walk
3. array_filter
But I haven't managed to nail down the best, most efficient way. I want to have a tool that will filter through a list of 20k+ sites against a list of keywords that may be up to 1k long, so performance is paramount. Also, what would be the better method for the actual search in this case - regex
or strpos
?
What other options are there to do this and what would be the best way?
Short solution using preg_grep function:
$result = preg_grep('/'. implode('|', $bad_keywords) .'/', $sites, 1);
print_r($result);
The output:
Array
(
[0] => youtube.com
[3] => walmart.com
[4] => thezoo.com
[5] => etc.com
)