Reputation: 169
My problem is that I have a huge array. In this array are the Browser, the user used to get on my website, but also bots and spiders.
It looks like this: Mozilla, Mozilla, Mozillabot, Mozilla, Unicornbot and so on.
I need to get every key in my array, that have 'bot' in it like mozillabot, unicornbot.
But I cant find something.
array_search
doesn't work, array_keys
too.
Does anyone know a solution in Laravel?
Upvotes: 2
Views: 2476
Reputation: 7283
You can use the array_where
helper.
Along with the str_contains
string helper like so
$array = ["Mozilla", "Mozilla", "Mozillabot", "Mozilla", "Unicornbot"];
$bots = array_where($array, function ($key, $value) {
return str_contains(strtolower($value),array('bot'));
});
Or with the str_is
string helper, which uses pattern matching, like this
$bots = array_where($array, function ($key, $value) {
return str_is('*bot*',strtolower($value));
});
The check is done against lowercase strings to avoid variations on "Bot", "BOT" and so on.
Upvotes: 0
Reputation: 2112
You can use laravel helper functions
$array = ['Mozilla', 'Mozilla', 'Mozillabot', 'Mozilla', 'Unicornbot'];
$array = array_where($array, function($key, $value)
{
return str_contains($value, 'bot');
});
Upvotes: 0
Reputation: 44526
You can use the Crawler Detect library which makes it really easy to identify bots/crawlers/spiders. It can be as simple as a couple of lines of code. Below is a snippet taken from the library's documentation:
use Jaybizzle\CrawlerDetect\CrawlerDetect;
$CrawlerDetect = new CrawlerDetect;
// Check the user agent of the current 'visitor'
if($CrawlerDetect->isCrawler()) {
// true if crawler user agent detected
}
// Pass a user agent as a string
if($CrawlerDetect->isCrawler('Mozilla/5.0 (compatible; Sosospider/2.0; +http://help.soso.com/webspider.htm)')) {
// true if crawler user agent detected
}
Upvotes: 1
Reputation: 1288
You could do something like this...
$newArray = [];
foreach ($array as $value) {
if (str_contains($value, ['bot', 'BOT', 'Bot'])) {
$newArray[] = $value;
}
}
This will cycle through the array and use the laravel str_contains function to determine wether or not the array value has the word 'bot' or variants in it and then add it to a new array.
Upvotes: 0